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

时间:2012-03-23 20:53:54

标签: c++ windows

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

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

在互联网上阅读时我得到了以下算法,我也不确定是否采用这种方法:

  1. 从流程名称中查找流程ID。
  2. 使用EnumWindows
  3. 枚举属于此进程ID的所有窗口
  4. 上面的步骤将为我提供类型为 - HWND
  5. 的窗口句柄变量
  6. 我可以通过传入这个HWND变量来设置焦点或设​​置前景。
  7. 我的问题在于语法方面,我真的不知道如何开始编写enumwindows,是否有人可以指向一组示例代码,或者您是否有指向我应该如何处理此问题的指针?

    谢谢。

2 个答案:

答案 0 :(得分:5)

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);
}

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

免责声明:未经测试但应该有效:)

答案 1 :(得分:3)

SetWindowPos(windowHandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_SHOWWINDOW|SWP_NOSIZE|SWP_NOMOVE);  // it will bring window at the most front but makes it Always On Top.

SetWindowPos(windowHandle, HWND_NOTOPMOST, 0, 0, 0,    0, SWP_SHOWWINDOW|SWP_NOSIZE|SWP_NOMOVE); // just after above call, disable Always on Top.