只知道進程ID,獲取主窗口句柄的方法如下:
- 通過EnumWindows枚舉所有窗口
- 使用GetWindowThreadProcessID,通過窗口句柄獲取進程ID
- 比便獲取的進程ID與當前已知的進程ID,判斷是否為需要的窗口
代碼如下:
function GetHwndFromProcess(const hPID: THandle): THandle; type PEnumInfo = ^TEnumInfo; TEnumInfo = record ProcessID: DWORD; HWND: THandle; end; function EnumWindowsProc(Wnd: DWORD; var EI: TEnumInfo): Bool; stdcall; var PID: DWORD; h: THandle; begin Result := True; GetWindowThreadProcessID(Wnd, @PID); if PID = EI.ProcessID then begin h := GetWindowLong(Wnd, GWL_HWNDPARENT); if h = 0 then begin EI.HWND := Wnd; Result := False; end; end; if not Result then EI.HWND := WND; end; function FindMainWindow(PID: DWORD): DWORD; var EI: TEnumInfo; begin EI.ProcessID := PID; EI.HWND := 0; EnumWindows(@EnumWindowsProc, Integer(@EI)); Result := EI.HWND; end; begin if hPID <> 0 then Result := FindMainWindow(hPID) else Result:=0; end;
by lin 2016-11-13