如何在事件发生时捕获我的进程ID?
Process pros = Process.Start(ProcessStartInfo);
pros.EnableRaisingEvents = true;
pros.Exited += pros_Exited;
private void pros_Exited(object sender, EventArgs e)
{
int processId = ??
}
答案 0 :(得分: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
// ...
};
}