您的位置:首页 > 其它

通过创建窗口进程的ID来查找窗口句柄

2010-04-30 12:33 627 查看
我们知道通过窗口句柄来查找创建这个窗口进程ID可以通过调用微软提供的API函数:

DWORD GetWindowThreadProcessId(
HWND hWnd, // Handle to the window.
LPDWORD lpdwProcessId // Pointer to a 32-bit value that receives the process identifier
);

即可。但是如果要反过来,通过创建窗口进程的ID来查找窗口句柄要怎么办呢?去MSND找,结果微软没有为我们提供这个API供我们使用。没有办法,现在只有我们自己去实现它哦!我这里用到了两个API :GetWindowThreadProcessId EnumWindows

BOOL EnumWindows(
WNDENUMPROC lpEnumFunc,// Long pointer to an application-defined callback function
LPARAM lParam //Specifies an application-defined value to be passed to the callback function
);

实现如下:
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;
}

之后我们们可以将创建窗口进程的ID作为参数传入到myGetWindowByProcessId函数里返回来的值就是与之对应的窗口句柄。

即:
HWND hWnd = myGetWindowByProcessId( dwProcessId );
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: