I have a custom ApplicationContext and I'm trying to terminate it if specific conditions are met. I am using a Mutex to ensure a single instance.
I've tried base.OnMainFormClosed(null, null);
. Application.Exit()
and ExitThread
. Everything stops processing, but the process itself is still running.
Complete Main() method:
static void Main()
{
bool firstInstance;
using (Mutex mutex = new Mutex(true,
@"Global\MyApplication",
out firstInstance))
{
if (!firstInstance)
{
MessageBox.Show("Another instance is already running.");
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new CustomContext());
}
}
What's the correct technique?
Application.Run(new CustomContext());
That's okay, but you don't store a reference to the CustomContext object you created. There's thus no way to call its ExitThread method. Tweak it like this:
class Program {
private static CustomContext appContext;
[STAThread]
public static void Main() {
// Init code
//...
appContext = new CustomContext();
Application.Run(appContext);
}
public static void Quit() {
appContext.ExitThread();
}
}
Now you can simply call Program.Quit() to stop the message loop.
Check my answer in this thread for a better way to implement a single-instance app. The WindowsFormsApplicationBase class also offers the ShutdownStyle property, probably useful to you instead of ApplicationContext.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With