C#  •  Make a Singleton App

Listing 4. The named Mutex serves as a simple cross-process communication mechanism when you use the SingletonApp class to implement a singleton application. If the named Mutex is unowned, SingletonApp launches the app. Otherwise, it simply returns, causing the application to terminate because no window is pumping messages, and the Main method returns.

public class SingletonApp 
{
   static Mutex m_Mutex;
   public static void Run(Form mainForm)
   {
      if(IsFirstInstance())
      {
         Application.ApplicationExit += new 
            EventHandler(OnExit);
         Application.Run(mainForm);
      }
   }
   //Other versions of Run()
   static bool IsFirstInstance()
   {
      m_Mutex = new Mutex(false,"SingletonApp Mutex");

      bool owned = false;
      owned = m_Mutex.WaitOne(TimeSpan.Zero,false);
      return owned ;
   }
   static void OnExit(object sender,EventArgs args)
   {
      m_Mutex.ReleaseMutex();
      m_Mutex.Close();
   }
}
public class MyForm : Form
{
   Label m_Label;

   public MyForm()
   {
      InitializeComponent();
   }
   private void InitializeComponent()
   {…}
   static void Main() 
   {
      SingletonApp.Run(new MyForm());
   }
}