【问题标题】:C#: form.Close method, FormClosing event, and CloseReason event argument. Set custom CloseReason?C#:form.Close 方法、FormClosing 事件和 CloseReason 事件参数。设置自定义 CloseReason?
【发布时间】: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();方法没有任何接受任何参数的重载,所以有我可以设置的变量或我可以调用的替代方法吗?

【问题讨论】:

    标签: c# winforms events


    【解决方案1】:

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

    【讨论】:

    • 我希望不必为了执行此操作而定义另一个变量,但这并不像我最初设想的解决方法那么难看。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 2010-10-24
    相关资源
    最近更新 更多