MFC 查找窗口句柄 获取进程ID 通过ID查找句柄

typedef struct EnumFunArg

{

    HWND hWnd;

    DWORD dwProcessId;


}EnumFunArg;

BOOL CALLBACK lpEnumFunc(HWND hwnd, LPARAM lParam)

{

    EnumFunArg* pArg = reinterpret_cast<EnumFunArg*> (lParam);

    DWORD dwProcessId;

    GetWindowThreadProcessId(hwnd, &dwProcessId);

    if (dwProcessId == pArg->dwProcessId)

    {

        pArg->hWnd = hwnd;

        // 注意:当查找到了,应该返回FALSE中止枚举下去

        return FALSE;

    }

    return TRUE;//继续枚举下去直到所有顶层窗口枚举完为止

}

HWND myGetWindowByProcessId(DWORD dwProcessId)

{

    EnumFunArg arg;

    arg.dwProcessId = dwProcessId;

    arg.hWnd = 0;

    EnumWindows(lpEnumFunc, reinterpret_cast<LPARAM>(&arg));

    return arg.hWnd;

}


//关闭程序
BOOL SetProcessClose(CString strProcessName)
{
    PROCESSENTRY32 pe32;
    int nRet = 0;
    pe32.dwSize = sizeof(pe32);
    HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hProcessSnap == INVALID_HANDLE_VALUE)
    {
        //    printf("出错\n");
        return false;
    }
    BOOL bMore = ::Process32First(hProcessSnap, &pe32);
    while (bMore)
    {
        //TRACE("进程名称:%S\n", pe32.szExeFile);
        //TRACE("进程ID号:%u\n\n", pe32.th32ProcessID);
        bMore = ::Process32Next(hProcessSnap, &pe32);

        CString strCmp = pe32.szExeFile;
        nRet = strCmp.Find(strProcessName);
        if (nRet != -1)
        {
            HWND hWnd = myGetWindowByProcessId(pe32.th32ProcessID);
            HANDLE hProcess = NULL;
            CString aa = pe32.szExeFile;
            HWND Hwnd = ::FindWindow(NULL,L"Odin3 v3.14"); //获取句柄api
            hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
        //    BOOL AAA = PostMessage((HWND)hProcess, WM_QUIT, NULL, NULL);
            //break;
            continue;
        }
    }
    ::CloseHandle(hProcessSnap);
    return true;
}


版权声明:本文为qq_42095701原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。