2017年9月7日 星期四

取得外部程式的Handle

uses ShellAPI;


function EnumWindowsProc(Wnd: DWORD; var EI: TEnumInfo): Bool; stdcall;
var
  PID : DWORD;
begin
  GetWindowThreadProcessID(Wnd, @PID);
  Result := (PID <> EI.ProcessID) or
    (not IsWindowVisible(WND)) or
    (not IsWindowEnabled(WND));

    if not result then
      EI.HWND := WND;
end;

function TForm1.FindMainWindow(PID: DWORD): DWORD;
var
  EI : TEnumInfo;
begin
  EI.ProcessID := PID;
  EI.HWND := 0;
  EnumWindows(@EnumWindowsProc, Integer(@EI));
  Result := EI.HWND;
end;


procedure TForm1.Button1Click(Sender: TObject);
var
  SI : TStartupInfo;
  PI : TProcessInformation;
  H : THandle;
  S : String;
begin
  ZeroMemory(@SI, SizeOf(SI));
  ZeroMemory(@PI, SizeOf(PI));
  SI.cb := SizeOf(SI);
  if CreateProcess(nil, 'CALC.EXE', nil, nil, FALSE, 0 ,nil,nil, SI, PI) then
  begin
    //注意!
    WaitForInputIdle(PI.hProcess, INFINITE);

    //Application.ProcessMessages;
    Sleep(1000);

    H := FindMainWindow(PI.dwProcessID);
    if H > 0 then
    begin
      SetLength(S, 255);
      GetWindowText(H, PChar(S), 255);
      SetLength(S, StrLen(PChar(S)));
      ShowMessage(S);
    end;

    CloseHandle(PI.hProcess);
    CloseHandle(PI.hThread);
  end;
end;

沒有留言:

張貼留言