简体   繁体   English

如何在FormClosing事件中显示MessageBox以提示取消?

[英]How to display a MessageBox in a FormClosing event to prompt for cancellation?

I am using this code but it does not work, what am I doing wrong? 我正在使用此代码,但是它不起作用,我在做什么错?

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("This will close down the whole application. Confirm?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        MessageBox.Show("The application has been closed successfully.", "Application Closed!", MessageBoxButtons.OK);
    }
    else
    {
        e.Cancel = true;
        this.Activate();
    }
}

I'll guess that you copied this code from somewhere and forgot to actually subscribe the FormClosing event. 我猜您是从某个地方复制了此代码,却忘记了实际订阅FormClosing事件。 Common trap in C#, VB.NET uses the Handles keyword to avoid mistakes like that. 在C#中,常见陷阱是VB.NET使用Handles关键字来避免此类错误。 Select the form, click the lightning bolt icon in the Properties window and double-click FormClosing to add the code that subscribes the event. 选择表单,在“属性”窗口中单击闪电图标,然后双击FormClosing以添加用于订阅事件的代码。

That said, it doesn't actually make sense to write code like this. 也就是说,编写这样的代码实际上没有任何意义。 Events are for other code to get notifications, a class doesn't have to listen to its own events. 事件是供其他代码获取通知的类,而类不必侦听自己的事件。 In Winforms, every event is triggered by a protected OnXxxx() method that you can override. 在Winforms中,每个事件都是由您可以覆盖的受保护的OnXxxx()方法触发的。 You can cut and paste the code below and fall in the pit of success, it doesn't require any extra code like the event subscription code to work. 您可以在下面剪切和粘贴代码,以取得成功,不需要任何其他代码,例如事件订阅代码。 And best of all, it gives preference to custom event handlers first, the kind of code you don't know about (yet) and ought to get the first shot at dealing with the notification. 最重要的是,它首先优先考虑自定义事件处理程序,这是您尚不了解的代码类型(还),应该在处理通知时获得第一手的注意。

    protected override void OnFormClosing(FormClosingEventArgs e) {
        base.OnFormClosing(e);
        if (!e.Cancel) {
            if (MessageBox.Show("Really?", "Close", MessageBoxButtons.YesNo) != DialogResult.Yes) {
                e.Cancel = true;
            }
        }
    }

Does the event-handler attach to form ? 事件处理程序是否附在表单上? To check, go to form Properties then to Events tab and see if Form1_FormClosing is present against FormClosing event. 要进行检查,请转到“表单属性”,然后转到“事件”选项卡,然后查看是否存在针对FormClosing事件的Form1_FormClosing。

If this form has been opened with FormName.ShowDialog() , inside the FormClosing event it's not enough to set e.Cancel=True. 如果已使用FormName.ShowDialog()打开此表单,则在FormClosing事件内部不足以设置e.Cancel = True。
You need to set the FormName.DialogResult to DialogResult.None as clearly documented on MSDN 您需要将FormName.DialogResult设置为DialogResult.None,MSDN上明确记录的那样

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

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