c# - 检测表单关闭的原因

标签 c# winforms

如何检测 Windows 窗体的关闭方式?例如,如何确定用户是否单击了关闭表单的按钮,或者用户是否单击了右上角的“X”?谢谢。

更新:

忘记提到按钮调用 Application.Exit() 方法。

最佳答案

正如 bashmohandes 和 Dmitriy Matveev 已经提到的,解决方案应该是 FormClosingEventArgs。但正如 Dmitriy 所说,这不会对您的按钮和右上角的 X 产生任何影响。

为了区分这两个选项,您可以在表单中添加一个 bool 属性 ExitButtonClicked 并在调用 Application.Exit() 之前在按钮点击事件中将其设置为 true。

现在您可以在 FormClosing 事件中询问此属性,并在 case UserClosing 中区分这两个选项。

例子:

    public bool UserClosing { get; set; }

    public FormMain()
    {
        InitializeComponent();

        UserClosing = false;
        this.buttonExit.Click += new EventHandler(buttonExit_Click);
        this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
    }

    void buttonExit_Click(object sender, EventArgs e)
    {
        UserClosing = true;
        this.Close();
    }

    void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        switch (e.CloseReason)
        {
            case CloseReason.ApplicationExitCall:
                break;
            case CloseReason.FormOwnerClosing:
                break;
            case CloseReason.MdiFormClosing:
                break;
            case CloseReason.None:
                break;
            case CloseReason.TaskManagerClosing:
                break;
            case CloseReason.UserClosing:
                if (UserClosing)
                {
                    //what should happen if the user hitted the button?
                }
                else
                {
                    //what should happen if the user hitted the x in the upper right corner?
                }
                break;
            case CloseReason.WindowsShutDown:
                break;
            default:
                break;
        }

        // Set it back to false, just for the case e.Cancel was set to true
        // and the closing was aborted.
        UserClosing = false;
    }

关于c# - 检测表单关闭的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1623756/

相关文章:

C# System.Forms.标签

c# - 单元测试基于 umbraco 的网站

c# - 为什么控件由于其保护级别而无法访问?

winforms - 我应该使用什么设计模式来将对象模型状态的更改同步到 GUI 的状态?

c# - 如何将数据从 Windows 窗体应用程序发送到 Asp.Net Web 服务应用程序

c# - List<> 上的 LINQ to NHibernate 表达式

c# - 错误 XDG0008 : NumberBox is not supported in a Universal Windows Platform project

c# - Windows 窗体 : DataGridView Problem with backgroundcolor after sorting

c# Winform richtextbox字体差异

c# - 如何为WinForm应用程序创建全局资源文件?