使用eventhandler加载另一个表单

时间:2014-04-22 17:21:49

标签: c# .net winforms thread-safety

private void button1_Click(object sender, EventArgs e)
{
    Process p1 = new Process();
    p1.StartInfo.FileName
        = @"D:\Softwares\ftrScanApiEx_v3.2\ftrScanApiEx_v3.2\ftrScanApiEx.exe";
    p1.EnableRaisingEvents = true;
    p1.Exited += new EventHandler(p1_Exited);
    p1.Start();
}

private void p1_Exited(object sender, EventArgs e)
{
    Form3 f3 = new Form3();
    f3.Show();
    this.Hide();
}

即使没有错误,Form3也没有加载..任何想法为什么???

1 个答案:

答案 0 :(得分:2)

我认为,正如运行评论中所指出的,这确实是一个线程问题。在创建Form3之前调用UI线程。检查InvokeRequired和调用

private void p1_Exited(object sender, EventArgs e)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new Action(OnProcessExited));
    }
    else
    {
        OnProcessExited();
    }
}

private void OnProcessExited()
{
    Form3 f3 = new Form3();
    f3.Show();
    this.Hide();
}