检测原因形式闭幕 [英] Detect reason for form closing

查看:89
本文介绍了检测原因形式闭幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何检测如何在Windows窗体被关闭?例如,如何才能知道用户是否点击了一个按钮,关闭窗体或者如果右上角的X的用户点击?谢谢你。

How can I detect how a windows form is being closed? For example, how do I find out whether the user has clicked on a button which closes the form or if the user clicks on the "X" in the upper-right? Thank you.

更新:

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

Forgot to mention that the button calls the Application.Exit() method.

推荐答案

由于bashmohandes和德米特里Matveev已经提到的解决方案应该是FormClosingEventArgs。但正如德米特里也表示,这不会让你的按钮,并在右上角在X之间的差异。

As bashmohandes and Dmitriy Matveev already mentioned the solution should be the FormClosingEventArgs. But as Dmitriy also said, this wouldn't make any difference between your button and the X in the right upper corner.

要这两个选项区分,可以将布尔属性的 ExitButtonClicked 的在按钮点击事件调用权利之前Application.Exit()添加到窗体并将其设置为true。

To distinguish between these two options, you can add a boolean property ExitButtonClicked to your form and set it to true in the button Click-Event right before you call Application.Exit().

现在您可以在活动的FormClosing内问这个属性和机箱内的两个选项之间区别的 UserClosing

Now you can ask this property within the FormClosing event and distinguish between those two options within the 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;
    }

这篇关于检测原因形式闭幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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