失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 通过Windows进程ID获取窗口句柄

通过Windows进程ID获取窗口句柄

时间:2022-07-13 19:48:16

相关推荐

通过Windows进程ID获取窗口句柄

通过Windows进程ID获取窗口句柄

方法一:使用EnumWindows的方式

///< 枚举窗口参数typedef struct{HWND hwndWindow; // 窗口句柄DWORD dwProcessID; // 进程ID}EnumWindowsArg;///< 枚举窗口回调函数BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam){EnumWindowsArg *pArg = (EnumWindowsArg *)lParam;DWORD dwProcessID = 0;// 通过窗口句柄取得进程ID::GetWindowThreadProcessId(hwnd, &dwProcessID);if (dwProcessID == pArg->dwProcessID){pArg->hwndWindow = hwnd;// 找到了返回FALSEreturn FALSE;}// 没找到,继续找,返回TRUEreturn TRUE;}///< 通过进程ID获取窗口句柄HWND CProcessTimeRestart::GetWindowHwndByPID(DWORD dwProcessID){HWND hwndRet = NULL;EnumWindowsArg ewa;ewa.dwProcessID = dwProcessID;ewa.hwndWindow = NULL;EnumWindows(EnumWindowsProc, (LPARAM)&ewa);if (ewa.hwndWindow){hwndRet = ewa.hwndWindow;}return hwndRet;}

方法二:使用GetTopWindow和GetNextWindow的方式

///< 枚举窗口参数typedef struct{HWND hwndWindow; // 窗口句柄DWORD dwProcessID; // 进程ID}EnumWindowsArg;///< 枚举窗口回调函数BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam){EnumWindowsArg *pArg = (EnumWindowsArg *)lParam;DWORD dwProcessID = 0;// 通过窗口句柄取得进程ID::GetWindowThreadProcessId(hwnd, &dwProcessID);if (dwProcessID == pArg->dwProcessID){pArg->hwndWindow = hwnd;// 找到了返回FALSEreturn FALSE;}// 没找到,继续找,返回TRUEreturn TRUE;}///< 通过进程ID获取窗口句柄HWND CProcessTimeRestart::GetWindowHwndByPID(DWORD dwProcessID){HWND hwndRet = NULL;EnumWindowsArg ewa;ewa.dwProcessID = dwProcessID;ewa.hwndWindow = NULL;EnumWindows(EnumWindowsProc, (LPARAM)&ewa);if (ewa.hwndWindow){hwndRet = ewa.hwndWindow;}return hwndRet;}

通过以上两种窗口获得的句柄,和使用FindWindow获得的句柄是一样的。

可以通过SendMessage向窗口发送消息

HWND hwnd = ::FindWindow(NULL, "Test");::SendMessage(hwnd, WM_CLOSE, 0, 0);

如果觉得《通过Windows进程ID获取窗口句柄》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。