Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Application.Shutdown()从上下文菜单失败_C#_Wpf_Delegates_Contextmenu - Fatal编程技术网

C# Application.Shutdown()从上下文菜单失败

C# Application.Shutdown()从上下文菜单失败,c#,wpf,delegates,contextmenu,C#,Wpf,Delegates,Contextmenu,此WPF程序显示一个ContextMenu,其中包含一个标记为“Exit”的菜单项以及一个空窗口。选择“退出”应终止进程,但它只会关闭窗口和上下文菜单。我不想强行终止这个计划,而是干净利落地结束它 为什么在Click事件处理程序中调用Application.Shutdown()无法关闭程序 using System; using System.Windows; using System.Windows.Controls; class MyApp : Application { [ST

此WPF程序显示一个ContextMenu,其中包含一个标记为“Exit”的菜单项以及一个空窗口。选择“退出”应终止进程,但它只会关闭窗口和上下文菜单。我不想强行终止这个计划,而是干净利落地结束它

为什么在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;
    }
}

这可能是WPF在打开ContextMenu时出现的一个错误。我昨天也有同样的问题。我的解决办法是:

menuItem.Click += delegate {

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

};

但在我的例子中,我是在托盘(通知)图标上打开ContextMenu,所以我没有WPF父对象。在您的情况下,我将尝试使ContextMenu成为WPF窗口的子对象,或者首先使用PlacementTarget属性。

请参见此答案:您的关机模式设置为什么?关机模式是默认模式,仅限LastWindowClose。@VinayC:我遵循了您提供的链接,但我不理解其相关性。您能解释一下吗?可能还有另一个线程设置为
false
?+1。实际上,在我隔离这个问题之前,我的代码还打开了一个
ContextMenu
,上面有一个
NotifyIcon
!你的代码看起来很有效;非常感谢。我不知道如何确认这是一个bug,所以我不确定您的解决方法是否总是有效,这让我有点犹豫是否立即将您的答案标记为已接受。