C# 当进程终止时,如何获取进程运行时
嗯。。。我的目标是当记事本终止textbox1.text中显示的运行时;C# 当进程终止时,如何获取进程运行时,c#,winforms,C#,Winforms,嗯。。。我的目标是当记事本终止textbox1.text中显示的运行时; 我认为问题可能是“for and break”而不是用WaitForExit()阻塞用户界面,捕获返回的进程,打开,然后连接事件。不过,您需要封送回UI线程进行更新(有许多不同的方法): 如果您希望所有内容都包含在按钮单击处理程序中: private void button1_Click(object sender, EventArgs e) { Process P = Process.Start("no
我认为问题可能是“for and break”而不是用
WaitForExit()
阻塞用户界面,捕获返回的进程,打开,然后连接事件。不过,您需要封送回UI线程进行更新(有许多不同的方法):
如果您希望所有内容都包含在按钮单击处理程序中:
private void button1_Click(object sender, EventArgs e)
{
Process P = Process.Start("notepad");
P.EnableRaisingEvents = true;
P.Exited += P_Exited;
}
private void P_Exited(object sender, EventArgs e)
{
Process P = (Process)sender;
textBox1.Invoke((MethodInvoker)delegate
{
textBox1.Text = (DateTime.Now - P.StartTime).ToString();
});
}
另一种变体使用循环和:
,并且过程
有一个方法。我相信你可以在那里做点什么来确定进程运行的时间。
private void button1_Click(object sender, EventArgs e)
{
Process P = Process.Start("notepad");
P.EnableRaisingEvents = true;
P.Exited += P_Exited;
}
private void P_Exited(object sender, EventArgs e)
{
Process P = (Process)sender;
textBox1.Invoke((MethodInvoker)delegate
{
textBox1.Text = (DateTime.Now - P.StartTime).ToString();
});
}
private async void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
Process P = Process.Start("notepad");
await Task.Run(() => {
P.WaitForExit();
});
textBox1.Text = (DateTime.Now - P.StartTime).ToString();
button1.Enabled = true;
}
private async void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
Process P = Process.Start("notepad");
await Task.Run(() =>
{
while (!P.HasExited)
{
Thread.Sleep(100);
textBox1.Invoke((MethodInvoker)delegate {
textBox1.Text = (DateTime.Now - P.StartTime).ToString();
});
}
});
textBox1.Text = (DateTime.Now - P.StartTime).ToString();
button1.Enabled = true;
}