代码之家  ›  专栏  ›  技术社区  ›  Tester101

启动进程并侦听退出事件

  •  4
  • Tester101  · 技术社区  · 16 年前

    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
    }
    

    我对德尔福了解不多,所以我们非常感谢您的帮助,谢谢。

    1 回复  |  直到 16 年前
        1
  •  9
  •   Jim McKeeth    6 年前

    是的,你可以用Delphi做类似的事情。我还没有看到使用事件处理程序,但您可以创建一个流程,等待它完成,然后在发生这种情况时执行某些操作。如果你想同时做点什么,就把它放在另一个线程中。

    下面是一些代码,用于创建流程并等待我从网络上删除:

    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;