检查表格关闭的原因

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

更新:

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

正如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; } 

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

你需要为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, }