C#:form.Close方法、FormClosing事件和CloseReason事件参数。设置自定义关闭原因?
我正在开发一个基于C#的实用程序,它使用FormClosing事件,根据是否通过form.Close()以编程方式关闭窗体,该事件应该执行不同的操作;方法,或通过任何其他方式(用户单击X、程序退出等) FormClosingEventArgs中的FormClosingEventArgs有一个名为CloseReason的属性(属于枚举类型CloseReason) 关闭原因可能是:无、Windows关机、MdiFormClosing、用户关闭、TaskManagerClosing、FormOwnerClosing、ApplicationExitCall 理想情况下,有一种方法可以区分用户何时单击红色X和何时单击Close();方法被调用(通过在执行其他操作后单击“继续”按钮)。但是,FormClosingEventArgs中的CloseReason属性在这两种情况下都设置为UserClosing,因此无法区分用户何时有意关闭表单以及何时以编程方式关闭表单。这与我的预期相反,如果任意调用Close()方法,CloseReason将等于NoneC#:form.Close方法、FormClosing事件和CloseReason事件参数。设置自定义关闭原因?,c#,winforms,events,C#,Winforms,Events,我正在开发一个基于C#的实用程序,它使用FormClosing事件,根据是否通过form.Close()以编程方式关闭窗体,该事件应该执行不同的操作;方法,或通过任何其他方式(用户单击X、程序退出等) FormClosingEventArgs中的FormClosingEventArgs有一个名为CloseReason的属性(属于枚举类型CloseReason) 关闭原因可能是:无、Windows关机、MdiFormClosing、用户关闭、TaskManagerClosing、FormOwner
//GuideSlideReturning is an cancelable event that gets fired whenever the current "slide"-form does something to finish, be it the user clicking the Continue button or the user clicking the red X to close the window. GuideSlideReturningEventArgs contains a Result field of type GuideSlideResult, that indicates what finalizing action was performed (e.g. continue, window-close)
private void continueButton_Click(object sender, EventArgs e)
{ //handles click of Continue button
GuideSlideReturningEventArgs eventArgs = new GuideSlideReturningEventArgs(GuideSlideResult.Continue);
GuideSlideReturning(this, eventArgs);
if (!eventArgs.Cancel)
this.Close();
}
private void SingleFileSelectForm_FormClosing(object sender, FormClosingEventArgs e)
{ //handles FormClosing event
if (e.CloseReason == CloseReason.None)
return;
GuideSlideReturningEventArgs eventArgs = new GuideSlideReturningEventArgs(GuideSlideResult.Cancel);
GuideSlideReturning(this, eventArgs);
e.Cancel = eventArgs.Cancel;
}
问题是当关闭()时;方法,则FormClosing事件处理程序无法判断窗体是通过该方法关闭的,而不是由用户关闭的
理想的情况是,我可以定义FormClosing事件的FormClosingEventArgs CloseReason是什么,如下所示:
this.Close(CloseReason.None);
有办法做到这一点吗?form.Close();方法没有任何接受任何参数的重载,因此是否可以设置变量或调用其他方法?在以编程方式调用close之前设置标志。这可以封装在私有方法中:
private bool _programmaticClose;
// Call this instead of calling Close()
private void ShutDown()
{
_programmaticClose = true;
Close();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing();
_programmaticClose = false;
}
在以编程方式调用close之前设置标志。这可以封装在私有方法中:
private bool _programmaticClose;
// Call this instead of calling Close()
private void ShutDown()
{
_programmaticClose = true;
Close();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing();
_programmaticClose = false;
}
我希望不必为了实现这一点而定义另一个变量,但这并没有我最初设想的解决方法那么难看。谢谢我希望不必为了实现这一点而定义另一个变量,但这并没有我最初设想的解决方法那么难看。谢谢