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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM