C# WINForm 避免两个消息框 [英] C# WINForm avoid two message box

查看:28
本文介绍了C# WINForm 避免两个消息框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一个退出"按钮的 GUI 程序.当点击这个按钮时,它会调用 Application.Exit() 来关闭这个程序.在关闭程序之前,它还会调用一个确认消息框.我还为这个 GUI 主窗体实现了关闭事件.在这种情况下,它还会调用一个确认消息框,然后调用 Application.Exit().

I have a GUI program with one "Exit" button. When clicking this button, it would call the Application.Exit() to close this program. Before closing the program, it also calls a confirm message box. I also implement the Closing Event for this GUI main form. In this event, it also calls a confirm message box, then calls the Application.Exit().

现在,当我关闭 GUI 时,它会弹出一个确认消息框,然后关闭它,一切正常.当我单击退出"按钮时,它会弹出两次确认消息框.我认为当它调用 Application.Exit() 时,会调用 Closing 事件.

Now, When I just close the GUI, it would popup a confirm message box, then close it, all is fine. 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.

有什么方法可以避免两次确认消息框?

Is there any method to avoid twice confirm message box?

此致,

推荐答案

这应该就是您所需要的.在您的表单上调用 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.

    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();
    }

如果您的应用程序的逻辑没有导致应用程序在表单关闭后退出,您应该像这样在 Form_Closed 事件中调用 Application.Exit :

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:

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

这篇关于C# WINForm 避免两个消息框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆