Search code examples
delphiexecutablehandleauto-update

How to check is there a process running with the given handle


Scenario: From App1, I need to execute App2 passing App1.Handle as param. App2 should wait until App1's close. After this, App2 should replace App1.exe file with an updated version.

  • Are there better ways to update a running executable file?
  • If there aren't.. In App2, I know App1.Handle and I should check if App1 has been closed. How can this be verified starting from App1.Handle?

EDIT:

App1:

var
  ProcessHandle : THandle;
begin
  ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, GetCurrentProcessId());
  //Is PROCESS_ALL_ACCESS needed?
  ShellExecute(0, 'open', 'App2.exe', PChar(IntToStr(ProcessHandle)), '.\', SW_SHOW);
end;

App2:

var
  SenderHandle : THandle;
begin
  if(ParamStr(1) <> '') then
  begin
    SenderHandle := StrToInt(ParamStr(1));
    WaitForSingleObject(SenderHandle, INFINITE);
    ShowMessage('App1 Terminated!');
    //Showmessage is executed when App1 is still running, what's wrong?
  end;
end;

Solution

  • App1.Handle implies a window handle. App2 needs to wait on App1's process handle instead. To get App1's process handle, use OpenProcess() with GetCurrentProcessId() as the process ID, or DuplicateHandle() with GetCurrentProcess() as the source handle. Then you can pass the handle to App2, and have App2 wait on it using WaitForSingleObject(). The handle will be signaled when App1 exits. Then App2 can close the handle and replace App1.exe.