如何检测窗体是如何关闭的?例如,如何确定用户是否单击了关闭表单的按钮,或者用户是否点击了右上角的“X”?谢谢。
更新
忘记提到按钮调用Application.Exit()方法。
答案 0 :(得分: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;
}
答案 1 :(得分:4)
您可以在FormClosing事件处理程序中检查FormClosingEventArgs的CloseReason属性,以检查一些可能的情况。但是,如果您仅使用此属性,则您描述的案例将无法区分。您需要在“关闭”按钮的单击事件处理程序中编写一些额外的代码,以存储一些将在FormClosing事件处理程序中检查的信息,以区分这些情况。
答案 2 :(得分:0)
你需要向Even FormClosing添加一个监听器,它会在事件args中发送一个类型为CloseReason的属性,这是其中一个值
// Summary:
// Specifies the reason that a form was closed.
public enum CloseReason
{
// Summary:
// The cause of the closure was not defined or could not be determined.
None = 0,
//
// Summary:
// The operating system is closing all applications before shutting down.
WindowsShutDown = 1,
//
// Summary:
// The parent form of this multiple document interface (MDI) form is closing.
MdiFormClosing = 2,
//
// Summary:
// The user is closing the form through the user interface (UI), for example
// by clicking the Close button on the form window, selecting Close from the
// window's control menu, or pressing ALT+F4.
UserClosing = 3,
//
// Summary:
// The Microsoft Windows Task Manager is closing the application.
TaskManagerClosing = 4,
//
// Summary:
// The owner form is closing.
FormOwnerClosing = 5,
//
// Summary:
// The System.Windows.Forms.Application.Exit() method of the System.Windows.Forms.Application
// class was invoked.
ApplicationExitCall = 6,
}