Search code examples
.netmutexrestart

Force Single Instance with Mutex handling restart application


I have a problem when i want use mutex to force single instance of my program.

I a winform App with a WebBrowser Control. I need to autorestart if certain conditions are met.

My Problem is that if i restart the application the mutex want let me open a new instance (this doesn't always happen) maybe cause browser has some async method like navigate.

But i release the Mutex in Exit Application Event.

This is my Code:

    static Mutex _mutex = new Mutex (false, "myprogramkey");

    [STAThread]
    private static void Main()
    { 
         Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
      if(_mutex.WaitOne(TimeSpan.FromSeconds(5), true))
      { 
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          Application.Run(new RevolutionForm()); 
      }

     else
      {
          MessageBox.Show("Error!");
      }
    }
        static void Application_ApplicationExit(object sender, EventArgs e)
    {
        _mutex.ReleaseMutex();
    }

Solution

  • Single instance apps are well supported by the framework. It supports goodies such as disabling it on-the-fly, what you need here, and getting a notification when another instance is started. You'll want to use that to give your first instance the focus. Rewrite your Program.cs code like this:

    using System;
    using System.Windows.Forms;
    using Microsoft.VisualBasic.ApplicationServices;   // NOTE: add reference to Microsoft.VisualBasic
    
    namespace WindowsFormsApplication1 {
        class Program : WindowsFormsApplicationBase {
            public Program() {
                EnableVisualStyles = true;
                MainForm = new Form1();
                IsSingleInstance = true;
            }
            public static void Main(string[] args) {
                Instance = new Program();
                Instance.Run(args);
            }
            protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) {
                // Nicety, focus the single instance.
                Instance.MainForm.Activate();
            }
            public static void Restart() {
                // What you asked for.  Use Program.Restart() in your code
                Instance.IsSingleInstance = false;
                Application.Restart();
            }
            private static Program Instance;
        }
    }