struct _PidHwnd { DWORD m_dwPid; HWND m_hWnd; }; BOOL CALLBACK _EnumWins(IN HWND h, IN LPARAM p) { if (p) { _PidHwnd *pItem = (_PidHwnd*)p; DWORD dwPid = 0; GetWindowThreadProcessId(h, &dwPid); /*句柄所属进程*/ if (dwPid == pItem->m_dwPid && IsWindowVisible(h) && 0 == GetParent(h)) /*顶层可见窗口*/ { pItem->m_hWnd = h; return FALSE; /*成功匹配,退出枚举*/ } } return TRUE; /*继续枚举*/ } HWND GetTopWnd1(IN DWORD dwPid) { _PidHwnd item = { 0 }; item.m_dwPid = dwPid; EnumWindows(_EnumWins, (LPARAM)&item); return item.m_hWnd; } int main() { STARTUPINFO si = { 0 }; si.cb = sizeof(si); PROCESS_INFORMATION pi = { 0 }; BOOL b = CreateProcess(_T("C:\\Using\\winmine.exe"), 0, 0, 0, 0, 0, 0, 0, &si, &pi); HWND h = 0; if (b) { for (int i = 0; i < 5 && !h; ++i) { h = GetTopWnd1(pi.dwProcessId); Sleep(1000); } printf("%d %08X \r\n", h, h); } return 0; }
来源:https://www.cnblogs.com/dailycode/p/12460168.html