Wednesday, May 14, 2008

WinForms - Using Mutex to force only one instance of Form

   1: static class Program
   2:  {
   3:      ///<summary>
   4:      /// The main entry point for the application.
   5:      ///</summary>
   6:      [STAThread]
   7:      static void Main()
   8:      {
   9:          bool instanceCountOne = false;
  10:  
  11:          using (Mutex mtex = new Mutex(true, "MyRunningApp", out instanceCountOne))
  12:          {
  13:              if (instanceCountOne)
  14:              {
  15:                  Application.EnableVisualStyles();
  16:                  Application.SetCompatibleTextRenderingDefault(false);
  17:                  Application.Run(new Form1());
  18:                  mtex.ReleaseMutex();
  19:              }
  20:              else
  21:              {
  22:                  MessageBox.Show("An application instance is already running");
  23:              }
  24:          }
  25:      }
  26:  }

No comments:

Post a Comment