Reputation: 35
private void button2_Click(object sender, EventArgs e)
{
Process.Start("notepad");
for(; ; )
{
var pname = Process.GetProcessesByName("notepad");
foreach (var proc in pname)
{
try
{
if (pname.Length == 0) // when the process("notepad") is terminated
{
textBox1.Text = Convert.ToString(DateTime.Now - proc.StartTime);//textbox1.text = process(notepad)run time
}
break;
}
catch
{
MessageBox.Show("trouble");
}
}
}
}
Um... my goal is when the notepad has terminated the runtime showed in textbox1.text; I think maybe the problem is "for and break"
Upvotes: 0
Views: 105
Reputation: 39132
Instead of blocking your UI with WaitForExit()
, capture the returned Process
, turn on EnableRaisingEvents, then wire up the Exited event. You'll need to marshal back to the UI thread for your update though (many different ways to do that):
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();
});
}
If you'd rather have it all within the button click handler:
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;
}
Another variation using a loop and HasExited:
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;
}
Upvotes: 1