[英]C#: form.Close method, FormClosing event, and CloseReason event argument. Set custom CloseReason?
我正在使用一个基于C#的实用程序,该实用程序使用FormClosing事件,并且根据是否通过form.Close()以编程方式关闭该窗体,该事件应该执行不同的操作。 方法或其他任何方式(用户单击X,退出程序等)
FormClosing事件中的FormClosingEventArgs具有一个名为CloseReason的属性(枚举类型为CloseReason)。
CloseReason可以是:无,WindowShutDown,MdiFormClosing,UserClosing,TaskManagerClosing,FormOwnerClosing,ApplicationExitCall。
理想情况下,将有一种方法可以区分用户何时单击红色的X和何时单击Close()。 调用方法(通过在执行其他操作后单击“继续”按钮)。 但是,在两种情况下,FormClosingEventArgs中的CloseReason属性都设置为UserClosing,因此无法区分用户是何时关闭窗体还是以编程方式关闭窗体。 这与我的期望相反,如果任意调用Close()方法,CloseReason将等于None。
//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;
}
问题是当Close(); 在GuideGlideReturning事件完成后未取消而调用该方法的情况下,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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.