使用C++中的进程名称进入前窗

Fyl*_*lix 4 c++ windows

我是C++的初学者(一直是C#),我接受了用C++编写的遗留程序的麻烦/更新.

我有一个在窗口上运行的进程名称"setup.exe",我知道如何找到它的HANDLE和DWORD进程ID.我知道它有一个窗口肯定但我似乎无法找到如何将此窗口带到前台,这就是我想要做的事情: 使用其进程名称将窗口带到前台.

在互联网上阅读后,我得到了以下算法,我也不确定是否正确的方法:

  1. 从进程名称中查找进程ID.
  2. 使用EnumWindows枚举属于此进程ID的所有窗口
  3. 上面的步骤将为我提供类型为HWND的窗口句柄变量
  4. 我可以通过传入这个HWND变量来设置焦点或设​​置前景.

我的问题在于语法方面,我真的不知道如何开始编写enumwindows,任何人都可以指向一组示例代码,或者如果你有任何指针我应该如何处理这个问题?

谢谢.

Kar*_*nek 6

EnumWindows过程评估所有顶级窗口.如果您确定要查找的窗口是顶级,则可以使用以下代码:

#include <windows.h>

// This gets called by winapi for every window on the desktop
BOOL CALLBACK EnumWindowsProc(HWND windowHandle, LPARAM lParam)  {
    DWORD searchedProcessId = (DWORD)lParam;  // This is the process ID we search for (passed from BringToForeground as lParam)
    DWORD windowProcessId = 0;
    GetWindowThreadProcessId(windowHandle, &windowProcessId); // Get process ID of the window we just found
    if (searchedProcessId == windowProcessId)  {  // Is it the process we care about?
      SetForegroundWindow(windowHandle);  // Set the found window to foreground
      return FALSE;  // Stop enumerating windows
    }
    return TRUE;  // Continue enumerating
}

void BringToForeground(DWORD processId)  {
   EnumWindows(&EnumWindowsProc, (LPARAM)processId);
}
Run Code Online (Sandbox Code Playgroud)

然后BringToForeground使用您想要的进程ID 调用.

免责声明:未经测试但应该工作:)

  • 当然,您需要成为当前的前台进程才能调用SetForegroundWindow. (3认同)