在事件的FormClosing

在事件的FormClosing

本文介绍了" e.Cancel"在事件的FormClosing的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用的FormClosing 事件,为什么代码 e.Cancel = TRUE; 的工作,但新CancelEventArgs()取消= TRUE;?不起作用

 私人无效Form1_FormClosing(对象发件人,FormClosingEventArgs E)
{
e.Cancel = TRUE;

新CancelEventArgs()取消= TRUE;
}


解决方案

本次活动由募集的WinForms管道代码。可以看到,自定义事件处理程序要改变默认行为的唯一方法是通过电子对象。创建一个新的CancelEventArgs对象没有副作用,该管道可以检测到。



有别的东西不对,事件引发对外部代码的好处,让它知道什么是怎么回事,给它一个选项来改变行为。没有外部代码在这里,该事件处理程序实际上是引发事件同一类的一部分。换言之,所述表格是听其自己的事件。有一个更好的方式来处理,你重写引发事件的方法。像这样的:

 保护覆盖无效OnFormClosing(FormClosingEventArgs E){
e.Cancel = TRUE;
base.OnFormClosing(E);
}

现在外部代码可以覆盖默认行为,事件引发的之后的该OnXxxx方法运行。和你有一个选择,如果你不希望外部代码重写的行为,简单地交换两个语句。


When using the FormClosing event, why does the code e.Cancel = true; work, but new CancelEventArgs().Cancel = true; does not work?

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true;

    new CancelEventArgs().Cancel = true;
}
解决方案

The event is raised by the Winforms plumbing code. The only way it can see that the custom event handler wants to alter the default behavior is through the e object. Creating a new CancelEventArgs object has no side-effects that the plumbing can detect.

There's something else wrong, events are raised for the benefit of external code, letting it know what's going on and giving it an option to alter behavior. There is no external code here, the event handler is actually part of the same class that raises the event. In other words, the form is listening to its own events. There's a much better way to deal with that, you override the method that raises the event. Like this:

    protected override void OnFormClosing(FormClosingEventArgs e) {
        e.Cancel = true;
        base.OnFormClosing(e);
    }

Now external code can override the default behavior, events are raised after the OnXxxx method runs. And you have a choice, if you do not want the external code to override the behavior, simply swap the two statements.

这篇关于" e.Cancel"在事件的FormClosing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:18