c++ - 将 PID 转换为 HWND

标签 c++ winapi process

基本上,我想将进程 ID 转换为 HWND。我正在使用这段代码:

   DWORD   dwWindowId;
   CHAR       pszClassName[200];
   HWND     hWnd;

   hWnd = GetTopWindow (NULL);

   while ( hWnd != NULL )
   {
      if ( GetClassName (hWnd, pszClassName, 200) > 0)
         if ( lstrcmpiA (lpcszWindowClass, pszClassName) == 0)
            if ( GetWindowThreadProcessId (hWnd, &dwWindowId) )
               if ( dwWindowId == dwProcessId )
                  return hWnd;

      hWnd = GetNextWindow ( hWnd, GW_HWNDNEXT );
   }
   return NULL;

在我尝试使用一个由 CreateProcess 创建的进程之前,它工作正常。在这种情况下我该怎么办?我从 CreateProcess 中获得了进程信息,例如它的 ID 和线程 ID,但我仍然不知道如何获取它的 hwnd。我读过这个:

After you call CreateProcess(), examine the PROCESS_INFORMATION struct pointed to by lpProcessInformation argument. PROCESS_INFORMATION contains a handle to the Process you just started and a Thread ID. With this information call the GetGUIThreadInfo()function and then examine the GUITHREADINFO struct pointed to by lpgui. GUITHREADINFO has several HWNDs. Start with hwndActive, and call GetParent() or GetAncestor() untill the Main window is found.

By bug_crusher

我试过 EnumChildWindows()EnumWindows(),但它们没有用。

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    DWORD PID =0;
    GetWindowThreadProcessId(hwnd,&PID);
    if(PID == 1)
    {
        //,,,,,,,,
    }
    return TRUE;
}

但是我不明白,谁能解释一下?

最佳答案

我对您实际尝试做的事情感到有点困惑,但此函数将构建属于指定进程的所有顶级窗口的 vector 。

void GetWindowsOfProcess(DWORD dwId, std::vector<HWND>& vecWindows)
{
    struct WindowsOfProcess
    {
        std::vector<HWND>*  pvecWindows;
        DWORD               dwProcId;

        static BOOL CALLBACK EnumProc(HWND hWnd, LPARAM lParam)
        {
            DWORD dwProcId;
            GetWindowThreadProcessId(hWnd, &dwProcId);
            if (dwProcId == reinterpret_cast<WindowsOfProcess*>(lParam)->dwProcId)
                reinterpret_cast<WindowsOfProcess*>(lParam)->pvecWindows->push_back(hWnd);
            return TRUE;
        }

        WindowsOfProcess(DWORD dwId, std::vector<HWND>* pvec)
            :   dwProcId(dwId)
            ,   pvecWindows(pvec)
        {
            EnumWindows(EnumProc, reinterpret_cast<LPARAM>(this));
        }
    };
    WindowsOfProcess wop(dwId, &vecWindows);
}

关于c++ - 将 PID 转换为 HWND,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17386902/

相关文章:

c# - 如何使用 C# 从其他进程在 Mingw 上运行命令?

C++ - 如何将 char append 到 char*?

C++ ODBC 检查连接是否成功

image - 如何使用 WinAPI ImageList_DrawIndirect 绘制透明图像?

c++ - C++ 的 RSA 加密库

c - Linux 内核 task_struct void *stack

python - 对于 Project Euler,C++ 似乎比 Python Ruby 慢得多

c++ - 最小和子 vector 算法

c - ListView 滚动条闪烁

linux - 如何在 Linux 中获取有关进程的信息