如何知道用户点击了“X"?或“关闭"按钮? [英] How to know user has clicked "X" or the "Close" button?

查看:34
本文介绍了如何知道用户点击了“X"?或“关闭"按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MSDN 中我发现 CloseReason.UserClosing 知道用户已决定关闭表单但我想单击 X 按钮或单击关闭按钮都是一样的.那么如何在我的代码中区分这两者?

In MSDN I found CloseReason.UserClosing to know that the user had decided to close the form but I guess it is the same for both clicking the X button or clicking the close button. So how can I differentiate between these two in my code?

谢谢大家.

推荐答案

假设您要求使用 WinForms,您可以使用 FormClosing() 事件.每当表单关闭时都会触发事件 FormClosing().

Assuming you're asking for WinForms, you may use the FormClosing() event. The event FormClosing() is triggered any time a form is to get closed.

要检测用户是否单击了 X 或您的 CloseButton,您可以通过 sender 对象获取它.尝试将 sender 转换为 Button 控件,例如验证其名称为CloseButton".

To detect if the user clicked either X or your CloseButton, you may get it through the sender object. Try to cast sender as a Button control, and verify perhaps for its name "CloseButton", for instance.

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    if (string.Equals((sender as Button).Name, @"CloseButton"))
        // Do something proper to CloseButton.
    else
        // Then assume that X has been clicked and act accordingly.
}

否则,我从来不需要区分是 X 还是 CloseButton 被点击,因为我想对 FormClosing 事件执行一些特定的操作,比如在关闭 MDIContainerForm 之前关闭所有 MdiChildren,或者事件检查未保存的更改.在这种情况下,我认为我们不需要区分任何一个按钮.

Otherwise, I have never ever needed to differentiate whether X or CloseButton was clicked, as I wanted to perform something specific on the FormClosing event, like closing all MdiChildren before closing the MDIContainerForm, or event checking for unsaved changes. Under these circumstances, we don't need, according to me, to differentiate from either buttons.

通过 ALT+F4 关闭也会触发 FormClosing() 事件,因为它会向 Form 发送一条消息,说要关闭.您可以通过设置

Closing by ALT+F4 will also trigger the FormClosing() event, as it sends a message to the Form that says to close. You may cancel the event by setting the

FormClosingEventArgs.Cancel = true. 

在我们的例子中,这将转化为

In our example, this would translate to be

e.Cancel = true.

注意 FormClosing() 和 FormClosed() 事件.

Notice the difference between the FormClosing() and the FormClosed() events.

FormClosing 在表单收到要关闭的消息时发生,并在关闭之前验证它是否有事情要做.

FormClosing occurs when the form received the message to be closed, and verify whether it has something to do before it is closed.

FormClosed 在表单实际关闭时发生,所以在关闭之后.

FormClosed occurs when the form is actually closed, so after it is closed.

这有帮助吗?

这篇关于如何知道用户点击了“X"?或“关闭"按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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