Ensuring that only a single instance of a .NET application is running (2009-08-18)
[STAThread] static void Main() // args are OK here, of course { bool ok; m = new System.Threading.Mutex(true, "YourNameHere", out ok);
if (! ok) { MessageBox.Show("Another instance is already running."); return; }
Application.Run(new Form1()); // or whatever was there
GC.KeepAlive(m); // important! }
or
static void Main() { bool mutexCreated = false; System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );
if( !mutexCreated ) { if( MessageBox.Show( "slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?", "slimKEYS already running", MessageBoxButtons.YesNo, MessageBoxIcon.Question ) != DialogResult.Yes ) { mutex.Close(); return; } }
// The usual stuff with Application.Run()
mutex.Close(); }
|