delphi - 启动进程并监听退出事件

标签 delphi code-conversion

我有一些代码启动一个进程并连接一个事件处理程序来处理进程退出时的情况,我的代码是用 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 不太了解,所以任何帮助将不胜感激,谢谢。

最佳答案

是的,您可以使用 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;

关于delphi - 启动进程并监听退出事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2008553/

相关文章:

c++ - 将数据从 Delphi DLL 传递到 C++ 应用程序

delphi - 以两种不同的方式显示表单

c++ - 如何将 C++ _tcscpy、_tcscat 转换为 Delphi?

c# - 将 VB.Net 代码转换为 C# 时出现逻辑错误

java - 自动化 Java 到 Scala 源代码转换?

mysql - 将 MySQL 查询转换为 SQLite 查询

windows - 使用 Delphi 创建 Windows 用户

delphi - 如何将我的图表栏设置在底部而不是中心

delphi - 如果调用 FastReport.PrepareReport,则 ISAPI Web 应用程序挂起

java - 代码质量 - @Autowired 成员变量的顺序?