1

我的程序有多种形式。第五个也是最后一个表单有一个按钮,单击该按钮时使用方法 Application.Exit() 关闭应用程序。但是,每次单击该按钮时,我都会在第一个表单上收到围绕此代码的错误“无法访问已处理的对象”:

 frm2 f2 = new frm2();
            this.Hide();
            f2.ShowDialog();
            this.Show();

编译器指示该语句this.show()是问题所在。有人可以解释为什么我会收到此错误以及如何解决它吗?

4

2 回答 2

2

好的,编辑了我的答案,我复制了您的问题。如果要使用Form.ShowDialog,则应设置正在关闭应用程序的控件的 DialogResult。因此,在按钮属性中,您应该将对话框结果设置为某些内容,例如Cancel.

然后在按钮单击事件上,您将执行以下操作:

    private void btnClose_Click(object sender, EventArgs e)
    {
        if (this.DialogResult == DialogResult.Cancel)
        {
            Application.Exit();
        }
    }

否则如果你不需要使用Form.ShowDialog,你可以只显示Form2。以上在我的测试中不会产生错误。

于 2012-11-30T23:47:36.417 回答
0

In your code example, did frm2 make a call to Application.Exit? If it did, then why are you trying to call this.Show again?

Anyway, you may have a problem related to how you started the application's message loop. Are you running Application.Run(), or Application.Run(form1)?

If you provided a form to Application.Run() when you started your message loop, then you should not be calling Application.Exit in order to exit the application. Instead, you should simply close your main window, that would cause the message loop to finish, the call to Application.Run to return, and your application will terminate cleanly.

于 2012-12-01T00:18:50.717 回答