Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当进程终止时,如何获取进程运行时_C#_Winforms - Fatal编程技术网

C# 当进程终止时,如何获取进程运行时

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

嗯。。。我的目标是当记事本终止textbox1.text中显示的运行时;
我认为问题可能是“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;
}