Create a single instance of your application

Create a single instance of your application

 

To allow only once instance of an application, use mutex [1] found in the System.Threading.Mutex namespace

 static class Program
  {
    // Create a static instance of a mutex with a name
    // I've used a GUID in this instance
    static Mutex mutex = new Mutex(true, "{07446D41-8B13-4771-B3F4-5594FA510F57}");

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      // Blocks the current thread until the current instance receives a signal,
      // using a TimeSpan to specify the time interval and specifying whether to exit the synchronization domain before the wait.
      if (mutex.WaitOne(TimeSpan.Zero, true))
      {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Cupofdev());

        // Releases the Mutex once.
        mutex.ReleaseMutex();
      }
      else
      {
        MessageBox.Show("Multiple instances of this application is not allowed");
      }
    }
  }

References
https://msdn.microsoft.com/en-us/library/system.threading.mutex

Email Newsletter

Missing out on the latest Cupofdev.com developments? Enter your email below to receive future announcements direct to your inbox. An email confirmation will be sent before you will start receiving notifications - please check your spam folder if you don't receive this.