捕获进程.退出 id.

本文关键字:id 退出 进程 | 更新日期: 2023-09-27 18:32:20

如何在引发事件时捕获进程 ID?

 Process pros = Process.Start(ProcessStartInfo);
 pros.EnableRaisingEvents = true;
 pros.Exited += pros_Exited;
private void pros_Exited(object sender, EventArgs e)
{
    int processId = ??
}

捕获进程.退出 id.

您可以使用匿名函数来捕获Process变量:

Process pros = Process.Start(processStartInfo);
pros.EnableRaisingEvents = true;
pros.Exited += (object sender, EventArgs e) =>
{
    int processId = pros.Id;
    // ...
};

编辑:如果您打算在循环中使用上述符号,请确保您了解闭包。

foreach (Process process in myProcesses)
{
    process.EnableRaisingEvents = true;
    Process processInner = process;   // copy to inner variable
    processInner.Exited += (object sender, EventArgs e) =>
    {
        int processId = processInner.Id;   // always reference inner variable
        // ...
    };
}