C#中窗口表单应用程序中的关闭窗口警报

时间:2015-01-07 09:39:57

标签: c# winforms

当用户通过单击(X)或按 ESC 键或按 ALT + 关闭窗口(窗口表单应用程序,C#)时,我想要F4 ,将显示一个警告,即一个对话框(包含两个按钮OK& CANCEL)。 怎么办?

2 个答案:

答案 0 :(得分:0)

您可以通过简单的搜索找到它!

处理表单的Closing事件:

this.Closing += OnClosing; // For example put this in the constructor of your form

private void OnClosing(object sender, CancelEventArgs cancelEventArgs)
{
        string msg = "Do you want to close this?";
        DialogResult result = MessageBox.Show(msg, "Close Confirmation",
            MessageBoxButtons.YesNo/*Cancel*/, MessageBoxIcon.Question);
        if (result == DialogResult.Yes)
            /* Do something */;
        else if (result == DialogResult.No)
            cancelEventArgs.Cancel = false;

}

答案 1 :(得分:0)

您可以在应用程序级别执行此操作

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ApplicationExit += Application_ApplicationExit;
        AppDomain.CurrentDomain.ProcessExit += Application_ApplicationExit;
        Application.Run(new Form1());
    }
    static void Application_ApplicationExit(object sender, EventArgs e)
    {
        //Do something
    }