Delphi 通得进程ID获取主窗口句柄

只知道进程ID,获取主窗口句柄的方法如下:

  1. 通过EnumWindows枚举所有窗口
  2. 使用GetWindowThreadProcessID,通过窗口句柄获取进程ID
  3. 比便获取的进程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