简体   繁体   English

C#WINForm避免出现两个消息框

[英]C# WINForm avoid two message box

I have a GUI program with one "Exit" button. 我有一个带有“退出”按钮的GUI程序。 When clicking this button, it would call the Application.Exit() to close this program. 单击此按钮时,它将调用Application.Exit()关闭该程序。 Before closing the program, it also calls a confirm message box. 在关闭程序之前,它还会调用一个确认消息框。 I also implement the Closing Event for this GUI main form. 我还为该GUI主窗体实现了关闭事件。 In this event, it also calls a confirm message box, then calls the Application.Exit(). 在这种情况下,它还会调用一个确认消息框,然后调用Application.Exit()。

Now, When I just close the GUI, it would popup a confirm message box, then close it, all is fine. 现在,当我刚刚关闭GUI时,它将弹出一个确认消息框,然后将其关闭,一切都很好。 When I click the "Exit" Button, it would popup the confirm message box twice. 当我单击“退出”按钮时,它将弹出两次确认消息框。 I think when it call the Application.Exit(), the Closing event is invoked. 我认为当它调用Application.Exit()时,将调用Closing事件。

Is there any method to avoid twice confirm message box? 有什么方法可以避免两次确认消息框?

Best Regards, 最好的祝福,

What you could do is remove the confirm button from the Application.Exit() method and keep it just in the Closing Event. 您可以做的是从Application.Exit()方法中删除确认按钮,并将其保留在Closing Event中。 Then instead of calling Application.Exit() directly in your button click event, instead call Form.Close() method of the form; 然后,不要直接在按钮单击事件中调用Application.Exit(),而是调用表单的Form.Close()方法。

This should be all you need. 这应该是您所需要的。 Calling the Close method on your form will close the form, and if that is your only form running in the application, it will also end the application. 在您的窗体上调用Close方法将关闭该窗体,如果那是您在应用程序中运行的唯一窗体,它将也结束该应用程序。

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("Really want to close?", "Closing"
            , MessageBoxButtons.YesNo) == DialogResult.No)
        {
            e.Cancel = true;
        }
    }

    private void btnExit_Click(object sender, EventArgs e)
    {
        this.Close();
    }

If the logic around your app does not cause the application to exit after the form is closed, you should just call Application.Exit in the Form_Closed event like this: 如果关闭表单后应用程序周围的逻辑未导致应用程序退出,则应仅在Form_Closed事件中调用Application.Exit ,如下所示:

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.Exit();
    }

you could use a global lock object for your messages. 您可以为消息使用全局锁定对象。

whenever you feel like showing a message box you'd write something like this: 每当您想要显示一个消息框时,您都将编写如下内容:

lock (mymessages)
{
  if (!nomoremessages)
  {
    MessageBox.Show("Hi");
    nomoremessages = true;
  }
}

This shall ensure only the first message will ever be shown. 这将确保仅显示第一条消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM