C#:form.Close方法,FormClosing事件和CloseReason事件参数。设置自定义CloseReason?

时间:2012-08-18 03:03:40

标签: c# winforms events

我正在开发一个基于C#的实用程序,该实用程序使用FormClosing事件,并且该事件应该执行不同的操作,具体取决于表单是否通过form.Close()以编程方式关闭。方法,或其他任何东西(用户点击X,程序退出等)

FormClosing事件中的FormClosingEventArgs有一个名为CloseReason的属性(枚举类型为CloseReason)。

CloseReason可以是:None,WindowShutDown,MdiFormClosing,UserClosing,TaskManagerClosing,FormOwnerClosing,ApplicationExitCall。

理想情况下,有一种方法可以区分用户何时点击红色X和何时关闭();调用方法(在执行其他操作后单击“继续”按钮)。但是,在两种情况下,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();方法没有任何接受任何参数的重载,那么我可以设置一个变量或者我可以调用的替代方法吗?

1 个答案:

答案 0 :(得分:4)

在以编程方式调用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;
}