2012-04-06 53 views
1

此WPF程序显示一个ContextMenu,它包含一个标记为'Exit'的MenuItem以及一个空的Window。选择“退出”应该终止进程,但它只关闭窗口和ContextMenu。我并不想强行终止这个计划,而是干脆结束它。Application.Shutdown()从ContextMenu失败

为什么在Click事件处理程序中调用Application.Shutdown()无法关闭程序?

using System; 
using System.Windows; 
using System.Windows.Controls; 

class MyApp : Application { 

    [STAThread] 
    public static void Main() { 
     new MyApp().Run(); 
    } 

    protected override void OnStartup(StartupEventArgs e) { 

     new Window().Show(); 

     MenuItem menuItem = new MenuItem(); 
     menuItem.Header = "Exit"; 
     menuItem.Click += delegate { Shutdown(); }; 

     ContextMenu contextMenu = new ContextMenu(); 
     contextMenu.Items.Add(menuItem); 
     contextMenu.IsOpen = true; 
    } 
} 
+0

看到这个回答:http://stackoverflow.com/questions/606043/shutting-down-a-wpf-application-from-app-xaml-cs – VinayC 2012-04-06 04:10:54

+0

你的ShutdownMode设置为什么? – Flot2011 2012-04-06 04:28:43

+0

ShutdownMode是默认的OnLastWindowClose。 – 2012-04-06 04:45:58

回答

2

这可能是在打开ContextMenu时抛开WPF中的一个错误。我昨天也遇到了同样的问题。我的解决方法是:

menuItem.Click += delegate { 

    Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input, 
     (Action)(() => { Shutdown(); })); 

}; 

但在我的情况下,我在托盘打开文本菜单(通知)图标,所以我没有WPF父它。在你的情况下,我会尝试使WPF窗口的ContextMenu孩子或首先与PlacementTarget属性一起玩。

+0

+1。其实,在我解决问题之前,我的代码还在'NotifyIcon'上打开了一个'ContextMenu'!你的代码似乎有效;谢谢。我不知道如何确认这是一个错误,所以我不确定你的解决方法会一直工作,这让我有点犹豫是否马上接受了你的答案。 – 2012-04-11 03:31:16