1

This WPF program displays a ContextMenu hosting a MenuItem labeled 'Exit', along with an empty Window. Selecting 'Exit' should terminate the process, but it only closes the Window and ContextMenu. I am not looking to forcibly terminate this program, but end it cleanly.

Why does calling Application.Shutdown() in the Click event handler fail to shut down the program?

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;
    }
}
80386 DX
  • 135
  • 1
  • 2
  • 5
  • See this SO answer: http://stackoverflow.com/questions/606043/shutting-down-a-wpf-application-from-app-xaml-cs – VinayC Apr 06 '12 at 04:10
  • What your ShutdownMode is set to? – Flot2011 Apr 06 '12 at 04:28
  • The ShutdownMode is the default, OnLastWindowClose. – 80386 DX Apr 06 '12 at 04:45
  • @VinayC: I followed the link you provided, but I do not understand the relevance. Would you please explain? – 80386 DX Apr 06 '12 at 04:48
  • Is there perhaps another thread with [IsBackground](http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx) set to `false`? – Clemens Apr 06 '12 at 08:11
  • @EvAlex - I got my results using Visual C# 2010 Express on a Windows 7 Ultimate machine, and also running similar code in LINQPad 4.31. What was your build environment? Did you check for a windowless process in Task Manager after clicking 'Exit'? – 80386 DX Apr 06 '12 at 14:06
  • @Clemens - In this program, the only thread I am aware of is this WPF UI one. The code I provided above is the only code file in the program. – 80386 DX Apr 06 '12 at 14:10

1 Answers1

2

This is probably a bug in WPF when opening ContextMenu aside. I had exactly the same problem yesterday. My workaround is:

menuItem.Click += delegate {

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

};

But in my case I am opening ContextMenu over tray (notify) icon so I don't have WPF parent for it. In your case I would try to make ContextMenu child of WPF window or play with PlacementTarget property first.

Sunil D.
  • 17,983
  • 6
  • 53
  • 65
Marek
  • 21
  • 2
  • +1. Actually, before I isolated the issue my code also opened a `ContextMenu` over a `NotifyIcon`! Your code seems effective; thank you. I don't know how to confirm that this is a bug, so I'm not sure your workaround will always work, which leaves me a bit hesitant to mark your answer as accepted right away. – 80386 DX Apr 11 '12 at 03:31