Application.Current.Shutdown() is not killing my application

后端 未结 7 891
执念已碎
执念已碎 2021-02-05 03:39

I\'ve just started a new C#/WPF application and am using the NotifyIcon from the WPF Contrib project. I can start the program, add an \"Exit\" MenuItem to the NotifyIcon\'s Cont

7条回答
  •  忘了有多久
    2021-02-05 04:26

    You don't need to do that! just simply override OnClosing method inside the main window like this:

            protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
            {
                try
                {
                    // If you try to dispose it from ViewModel, you might get a CrossThreadException.
                    notifyIcon.Dispatcher.Invoke(new Action(delegate
                    {
                        notifyIcon.Dispose();
                    }));
                }
                catch { }
                base.OnClosing(e);
            }
    

    and then in everywhere of your main application code, no matter you are in View or ViewModel or everywhere, just call it like this:

    Application.Current.MainWindow.Close();
    

    I had the same problem but I fix it like that.

    Update: You should not use Environment.Exit(0); method. it throws the same exception.

提交回复
热议问题