Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit Application from ApplicationContext

Tags:

c#

.net

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?

like image 622
mattdwen Avatar asked Aug 04 '10 09:08

mattdwen


1 Answers

   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.

like image 78
Hans Passant Avatar answered Nov 12 '22 14:11

Hans Passant