Starting a process and listening for exit event

后端 未结 1 1843
青春惊慌失措
青春惊慌失措 2021-02-06 13:16

I have some code that starts a process and hooks up an event handler to handle when the process exits, the code I have is written in C# and I wonder if something similar is poss

相关标签:
1条回答
  • 2021-02-06 14:09

    Yes, you can do something similar with Delphi. I have not seen using an event handler, but you can create a process, wait for it to finish, and then do something when that happens. Put it in another thread if you want to do something in the meantime.

    Here is some code for creating a process and waiting that I scraped off the net:

    procedure ExecNewProcess(const 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
          //Note: This will wait forever if the process never ends! 
          // You are better off using a loop with a timeout, or WaitForMultipleObject 
          if Wait then
            WaitForSingleObject(ProcInfo.hProcess, INFINITE);
        end
      else
        begin
          RaiseLastOSError;
          //SysErrorMessage(GetLastError());
        end;
    
      CloseHandle(ProcInfo.hProcess);
      CloseHandle(ProcInfo.hThread);
    end;
    
    0 讨论(0)
提交回复
热议问题