Starting a process and listening for an exit event

I have a code that starts a process and hooks an event handler to handle when the process ends, the code I have is written in C #, and I wonder if something like this is possible with Delphi.

System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = "notepad.exe";
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new System.EventHandler(Process_OnExit);
myProcess.Start();

public void Process_OnExit(object sender, EventArgs e)
{
    //Do something when the process ends
}

I don't know much about Delphi, so any help would be appreciated, thanks.

+3
source share
1 answer

Yes, you can do something similar with Delphi. I have not seen the use of an event handler, but you can create a process, wait for it to complete, and then do something when this happens. Put it in another thread if you want to do something on average.

Here is the code to create the process and expect that I scraped the network:

procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
var
  StartInfo : TStartupInfo;
  ProcInfo : TProcessInformation;
  CreateOK : Boolean;
begin
    { fill with known state } 
  FillChar(StartInfo,SizeOf(TStartupInfo), 0);
  FillChar(ProcInfo,SizeOf(TProcessInformation), 0);
  StartInfo.cb := SizeOf(TStartupInfo);
  CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil,False,
              CREATE_NEW_PROCESS_GROUP or NORMAL_PRIORITY_CLASS,
              nil, nil, StartInfo, ProcInfo);
    { check to see if successful } 
  if CreateOK then
    begin
        //may or may not be needed. Usually wait for child processes 
      if Wait then
        WaitForSingleObject(ProcInfo.hProcess, INFINITE);
    end
  else
    begin
      //ShowMessage('Unable to run '+ProgramName);
      SysErrorMessage(GetLastError());
    end;

  CloseHandle(ProcInfo.hProcess);
  CloseHandle(ProcInfo.hThread);
end;
+6

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


All Articles