如何检测 Windows 窗体的关闭方式?例如,如何确定用户是否单击了关闭表单的按钮,或者用户是否单击了右上角的“X”?谢谢。
更新:
忘记提到按钮调用 Application.Exit() 方法。
最佳答案
正如 bashmohandes 和 Dmitriy Matveev 已经提到的,解决方案应该是 FormClosingEventArgs。但正如 Dmitriy 所说,这不会对您的按钮和右上角的 X 产生任何影响。
为了区分这两个选项,您可以在表单中添加一个 bool 属性 ExitButtonClicked 并在调用 Application.Exit() 之前在按钮点击事件中将其设置为 true。
现在您可以在 FormClosing 事件中询问此属性,并在 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;
}
关于c# - 检测表单关闭的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1623756/