0

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

 Process pros = Process.Start(ProcessStartInfo);
 pros.EnableRaisingEvents = true;
 pros.Exited += pros_Exited;

private void pros_Exited(object sender, EventArgs e)
{
    int processId = ??
}
4

1 回答 1

3

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

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

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

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
        // ...
    };
}
于 2013-09-21T20:18:13.553 回答