2012-03-23 70 views
4

我是C++的初学者(一直是C#),并且被用于处理用C++编写的旧程序的故障排除/更新。在C++中使用其进程名称进入前窗口

我有一个在窗口上运行的进程名“setup.exe”,我知道如何找到它的HANDLE和DWORD进程ID。我知道它有一个确定的窗口,但我似乎无法找到如何将此窗口置于前景,这是我正在尝试执行的操作:使用其进程名称将窗口置于前景。

在阅读我来到了以下算法,我也不能肯定在互联网上是做的正确方法:

  1. 查找进程名的进程ID。
  2. 属于使用EnumWindows
  3. 上述步骤这一过程ID枚举所有的窗户会给我的窗口句柄(S)型的可变 - HWND
  4. 我可以设置焦点或通过使在此设置前景HWND变量。

这里我的问题是语法明智的,我真的不知道该怎么开始写起来EnumWindows的,任何人可以点我向一组示例代码,或者如果您有任何指针,我应该如何处理这个问题?

谢谢。

+0

您可以搜索示例代码自己。您已经知道API名称是什么。尝试自己写点东西,并提出具体问题。按照现状来看,这太宽泛了。 Stack Overflow有数百万个EnumWindows问题。看看右边的列表。 – 2012-03-23 21:10:34

回答

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

然后,只需调用BringToForeground你想要的进程ID。

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

+3

当然,您需要成为当前的前台进程才能调用SetForegroundWindow。 – 2012-03-23 21:11:28

+0

谢谢,我试过这段代码,但是我一直在收到:错误C2065:'EnumWindowsProc':未声明的标识符。我试图在头文件中声明为静态布尔回调,但仍然没有运气。如果您有任何疑问,我会一直等待您的反馈..... – Fylix 2012-03-26 14:28:44

+0

谢谢Dark_Charlie,我在头文件中声明了回调函数。我现在得到了这个作品,我缺少的是将回调函数声明为变量。 – Fylix 2012-03-26 16:08:57

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. 
相关问题