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