检查表格关闭的原因

use*_*ser 26 c# winforms

如何检测窗体是如何关闭的?例如,如何确定用户是否单击了关闭表单的按钮,或者用户是否点击了右上角的"X"?谢谢.

更新:

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

Oli*_*ver 36

正如bashmohandes和Dmitriy Matveev已经提到的那样,解决方案应该是FormClosingEventArgs.但正如Dmitriy所说,这不会对你的按钮和右上角的X造成任何影响.

要区分这两个选项,可以在表单中添加一个布尔属性ExitButtonClicked,并在调用Application.Exit()之前在按钮Click-Event中将其设置为true.

现在,您可以在活动的FormClosing内问这个属性和机箱内的两个选项之间区别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;
    }
Run Code Online (Sandbox Code Playgroud)

  • 奥利弗,你现在犯了严重错误.如果您从单击处理程序调用Application.Exit,则关闭原因将是CloseReason.ApplicationExitCall和if(UserClosing)条件将无用.您应该在单击处理程序中调用this.Close()方法以匹配UserClosing开关案例,或者您需要将if语句移动到switch语句的外部. (2认同)

oku*_*ane 5

您可以在 FormClosing 事件处理程序中检查 FormClosingEventArgs 的 CloseReason 属性来检查一些可能的情况。但是,如果您仅使用此属性,则您所描述的情况将无法区分。您需要在“关闭”按钮的单击事件处理程序中编写一些额外的代码来存储一些信息,这些信息将在 FormClosing 事件处理程序中检查以区分这些情况。