5

我有一些代码可以启动一个进程并连接一个事件处理程序以在进程退出时进行处理,我拥有的代码是用 C# 编写的,我想知道 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
}

我对Delphi了解不多,所以任何帮助将不胜感激,谢谢。

4

1 回答 1

9

是的,你可以用 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;
于 2010-01-05T20:18:01.387 回答