Delphi Get EXE handle

Here is an example of how I'm doing it right now:

var
Client : String;
Handle : Integer;
begin
Client := 'Window Name';
GetWindowThreadProcessId(FindWindow(nil, PAnsiChar(Client)), @ProcessId);
Handle := OpenProcess(PROCESS_ALL_ACCESS, False, ProcessId);
end;

I would rather capture a process handle with its name exe ... Is this possible?

+3
source share
3 answers

You can use ProcessInfo :

var
  ProcessInfo : TProcessInfo;
  Process : TProcessItem;
  PID: Cardinal;
  ProcessHandle : THandle;
begin
  ProcessInfo := TProcessInfo.Create(nil);
  try
    Process := ProcessInfo.RunningProcesses.FindByName('Notepad.exe');
    if Assigned(Process) then
    begin
      PID := Process.ProcessID;
      ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS,False,PID);
      if ProcessHandle > 0 then
      try
        {Add your code here}
      finally
        CloseHandle(ProcessHandle);
      end;
  end;
  finally
    ProcessInfo.Free;
  end;
end;

If you do not like using a third-party component, you can study the source code of ProcessInfo to find out how it retrieves a list of running processes and their properties. This mainly refers to the Windows Tool Help API for most of its functions.

+2
source

Application.Handle?
, Delphi WinAPI. , VCL - .
, - : GLibWMI

+3

, vcldeveloper, , , .

(PID), , ( OP , ReadProcessMemory).

If the function for PID returns 0, this means that the process is most likely not running (or simply not found in the list of running processes)

function GetPIDbyProcessName(processName:String):integer;
var 
  GotProcess: Boolean; 
  tempHandle: tHandle; 
  procE: tProcessEntry32;
begin
  tempHandle:=CreateToolHelp32SnapShot(TH32CS_SNAPALL, 0); 
  procE.dwSize:=SizeOf(procE); 
  GotProcess:=Process32First(tempHandle, procE);
  {$B-} 
    if GotProcess and (procE.szExeFile <> processName) then 
      repeat GotProcess := Process32Next(tempHandle, procE); 
      until (not GotProcess) or (procE.szExeFile = processName); 
  {$B+}

  if GotProcess then 
    result := procE.th32ProcessID 
  else
    result := 0; // process not found in running process list

  CloseHandle(tempHandle);
end;

Then we will get / open the process descriptor from the received PID. All code / usage is as follows:

var myPID, myProcessHandle: integer;
begin
  myPID:=GetPIDbyProcessName('someExeName.exe');
  myProcessHandle:=OpenProcess(PROCESS_ALL_ACCESS,False,myPID);
end;

You must save myProcessHandleso that it is available
ReadProcessMemory(myProcessHandle...)as the first parameter.

Also, add them to your global sentences:
Winapi.Windows(for ReadProcessMemory and OpenProcess)
Winapi.tlHelp32(to get the PID variable tProcessEntry32)

0
source

Source: https://habr.com/ru/post/1788807/


All Articles