【发布时间】:2012-08-18 03:03:40
【问题描述】:
我正在开发一个使用 FormClosing 事件的基于 C# 的实用程序,并且该事件应该根据表单是否通过 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();方法在事件 GuideSlideReturning 完成后没有被取消时调用,FormClosing 事件处理程序无法判断表单是通过该方法关闭而不是被用户关闭。
如果我可以定义 FormClosing 事件的 FormClosingEventArgs CloseReason 是什么,那么理想的情况是:
this.Close(CloseReason.None);
有没有办法做到这一点? form.Close();方法没有任何接受任何参数的重载,所以有我可以设置的变量或我可以调用的替代方法吗?
【问题讨论】: