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
I think the author's answer is the best one here, but hasn't really been called out. Application.Shutdown()
seems to require to be executed on the dispatcher thread to work. Try this if you run into the problem:
Application.Current.Dispatcher.Invoke(Application.Current.Shutdown);
I have had the same problem in my application. In my start up module (Startup.cs) I found that this works for me:
Process.GetCurrentProcess().Kill();
The code is as follows:
class StartUp
{
[STAThread]
public static void Main()
{
try
{
Process[] processes = new Process[6];
App app = new App();
app.InitializeComponent();
app.Run();
Process.GetCurrentProcess().Kill(); //Must add this line after app.Run!!!
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
This goes directly to the process causing the hang. There is no need to iterate through multiple processes.
It may be living in the processes. Here's a sample of how I check / kill the process
const string str = "MRS_Admin";
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName.StartsWith(str))
{
Console.WriteLine(@"Killing process " + str);
process.Kill();
}
}
You coult try Environment.Exit(0);
It kills the process with the given exit code. Exit code 0 states the application terminated successfully. It might be more 'rude' or 'not-done' but perhaps this is what you are looking for.
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.
I found if I create threads that are not set to "background", the main window/etc will close, but the threads will keep runnings.
In other words, only background threads close themselves when the main thread ends. Regular threads, aka Thread.IsBackground = false, will keep the process running.
Try using thread.IsBackground = true;
P.S. I made the assumption that you used threads somewhere.