/ Published in: C#
Scott Hanselman describes a method of using VB libraries to handle single-instance checking to prevent multiple instances of an app from starting. A mutex seems to be a simpler solution.\r\n\r\nAdd this class as a sibling to Main and then, inside Main, call this static member: SingleInstanceCheck.Check();
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
Example usage: static void Main() { SingleInstanceCheck.Check(); ... Implementation: /// <summary> /// This checks for another instance of an app. /// Use inside Main() by calling SingleInstanceCheck.Check(); /// Include this class as a sibling to Main's class. /// If another instance of the app is detected, /// - A message box appears. /// - 'this' instance calls Exit. /// </summary> /// <example> /// static void Main() /// { /// MyApp.SingleInstanceCheck.Check(); /// Application.EnableVisualStyles(); /// Application.SetCompatibleTextRenderingDefault(false); /// Application.Run(new Form1()); /// } /// </example> public static class SingleInstanceCheck { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); static public void Check() { // http://snipplr.com/view/19272/ - C#, single-instance-check using mutex // http://iridescence.no/post/CreatingaSingleInstanceApplicationinC.aspx bool isOwnedHere = false; true, Application.ProductName, out isOwnedHere ); if (!isOwnedHere) // if owned by other process. { string message = string.Format("There is already a copy of the application {0} running.\n\nClick cancel to exit.", Application.ProductName); DialogResult x = MessageBox.Show(message, Application.ProductName + " already running", MessageBoxButtons.OKCancel); if (x == DialogResult.Cancel) // Cancel, but show the already-existing process. { Process me = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(me.ProcessName)) // Debug note: Set Enable the Visual Studio Hosting Process = false. { if (process.Id != me.Id) // If the ProcessName matches but the Id doesn't, it's another instance of mine. { SetForegroundWindow(process.MainWindowHandle); break; } } Environment.Exit(0); // This will kill my instance. } } } // volatile is intended to prevent GC. Otherwise, GC.KeepAlive(appStartMutex) might be needed. // This appears to be a concern in In release builds but not debug builds. static volatile System.Threading.Mutex appStartMutex; }