我想在表单中调用This.Close()之后设置表单的CloseReason.
通常,这个表单本身会调用This.Close()来关闭,但我想问用户他们是否真的要关闭表单,并发送一个包含一些信息的mbox.但我有这个:
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
if (MessageBox.Show("¿Desea Salir realmente?\nLa factura aun no ha sido pagada por lo que volverá a la pantalla anterior y podrá seguir agregando productos") == DialogResult.No)
{
e.Cancel = true;
}
}
base.OnFormClosing(e);
}
Run Code Online (Sandbox Code Playgroud)
但每次我调用This.Close(); CloseReason始终是UserClosing.
我可以在通话后设置它还是我必须处理不同的OnFormClosing?
Leo*_*ick 12
而不是创建额外的变量:
appClosing = true;
this.Close();
Run Code Online (Sandbox Code Playgroud)
你可以打电话:
Application.Exit();
Run Code Online (Sandbox Code Playgroud)
然后e.CloseReason将会平等
CloseReason.ApplicationExitCall
Run Code Online (Sandbox Code Playgroud)
这可能是你所追求的.
alb*_*ein 11
我不认为你可以做到这一点,我一直在做的是使用旗帜
appClosing = true;
this.Close();
Run Code Online (Sandbox Code Playgroud)
然后检查:
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing && !appClosing)
{
if (MessageBox.Show("¿Desea Salir realmente?\nLa factura aun no ha sido pagada por lo que volverá a la pantalla anterior y podrá seguir agregando productos") == DialogResult.No)
{
e.Cancel = true;
}
}
base.OnFormClosing(e);
}
Run Code Online (Sandbox Code Playgroud)
我开始这样做的方法是根据用户在表单上单击的内容将表单的DialogResult属性设置为不同的东西.
在按钮单击方法中:
private void FillOrder_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
// this.Close() is called automatically when you set DialogResult
// so the above line will close the form as well.
}
Run Code Online (Sandbox Code Playgroud)
这样,您可以在FormClosing方法中执行以下操作:
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
switch (e.CloseReason)
{
case CloseReason.UserClosing:
switch (this.DialogResult)
{
case DialogResult.OK:
// User has clicked button.
break;
case DialogResult.Cancel:
// User has clicked X on form, show your yes/no/cancel box here.
// Set cancel here to prevent the closing.
//e.Cancel = true;
break;
}
break;
}
}
Run Code Online (Sandbox Code Playgroud)
至于CloseReason总是被设置为UserClosing,它被用户可以启动的任何动作设置为该值,不能准确记住什么,但我很确定即使任务管理器强制终止是用户关闭.但是我可以确认在各种情况下设置其他枚举值,例如在应用程序仍在运行时关闭/重启.您甚至可以通过在开关中捕获所有关闭原因并取消关闭来停止关闭窗口.
CloseReason是一个包含以下成员的枚举:
None
WindowsShutDown
MdiFormClosing
UserClosing
TaskManagerClosing
FormOwnerClosing
ApplicationExitCall
Run Code Online (Sandbox Code Playgroud)
这让我相信它一般取决于与表格行为相关的条件(例如,关闭父表单会关闭它的孩子).因此,为了让arg说出CloseReason.ApplicationExitCall,必须从Application.Exit调用触发该事件.
与CloseReason.FormOwnerClosing相同,假设您的子表单是使用form.Show(Parent)调用的
如果您的目标是简单地获得表单关闭原因的额外信息,您可以将其作为公共属性或属性存储在表单对象中,以便稍后访问它,假设表单未被处理.
提供改变CloseReason的动机也可能有所帮助.
CloseReason msdn页面供参考 http://msdn.microsoft.com/en-us/library/system.windows.forms.closereason.aspx