关闭窗口事件运行两次或更多次 [英] Closing window event run twice or more

查看:92
本文介绍了关闭窗口事件运行两次或更多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的关闭窗口事件。

It is a simple closing window event.

void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                e.Cancel = true;
                Application curApp = Application.Current;
                curApp.Shutdown();
            }
            catch { }
        }



首先我点击红色x图标关闭窗口,通过调试代码(F10),我发现它运行了两次或更多。

例如:


First I click the red x icon to close the windows, by debugging the code with step over(F10), I just found that it run twice or more.
For example:

e.Cancel = true;



它运行多次。为什么?


It run more than one times. Why?

推荐答案

不,这不是事件。你展示的只是一个方法,它可能是也可能不是事件处理程序,事件是 Window.Closing 。只有在事件实例上定义的运算符+ =定义是否有处理程序,那是什么。



此外,请参阅我对该问题的评论。很可能,您根本不需要处理此事件,因为如果这是主窗口,应用程序将在没有您的帮助的情况下终止,因为 Application.Run 将返回执行该条目点方法,这个方法将返回。通常,使用此事件的主要原因是在 e.Cancel = true 的帮助下取消关闭。



如果某些代码,事件处理程序或不执行,当它应该只执行一次时执行多次,这是一个简单的补救措施:

No, this is not the event. What you show is just a method which may or may not be an event handler, of the event Window.Closing or not. Only the operator += defined on the event instances defines is there a handler or not and what is that.

Also, please see my comment to the question. Most likely, you don't need to handle this event at all, because, if this is the main window, the application will be terminated without your help, as Application.Run will return execution to the entry point method, and this method will return. Usually, main reason use this event is cancellation of closing with the help of e.Cancel = true.

If some piece of code, event handler or not, is executed more than once when it is supposed to be executed only once, this is the simple remedy:
  1. 在调试器下,在方法的第一行放置一个断点;在你的情况下,这是单词try。
  2. 在调试器下运行代码并观察该片段的多次执行。执行应停止在同一点上。
  3. 当它第一次停止时,打开一个名为调用堆栈的新调试窗口。
  4. 每次执行在中断时停止点,看看调用堆栈。单击调用堆栈窗口中的不同项目,您将能够找到来电的来源。
  5. 修复代码。
  6. 利润!



-SA


因为Application.Current.Shutdown()方法会导致窗口的Closing事件得到又被解雇了。如果您想立即终止申请,请致电:

Because Application.Current.Shutdown() method will cause the Closing event of the window to get fired again. If you want to terminate your application immediately you should call:
Environment.Exit(0);





或者你可以简单地避免在事件处理程序中将CancelEventArgs.Cancel属性设置为true。



Or you could simply avoid setting the CancelEventArgs.Cancel property to true in your event handler.


这篇关于关闭窗口事件运行两次或更多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆