Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force C# .net app to run only one instance in Windows? [duplicate]

Possible Duplicate:
What is the correct way to create a single instance application?

How to force C# .net app to run only one instance in Windows?

like image 731
jinsungy Avatar asked Oct 08 '08 18:10

jinsungy


2 Answers

I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded

using System.Threading;  [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd);  /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() {    bool createdNew = true;    using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))    {       if (createdNew)       {          Application.EnableVisualStyles();          Application.SetCompatibleTextRenderingDefault(false);          Application.Run(new MainForm());       }       else       {          Process current = Process.GetCurrentProcess();          foreach (Process process in Process.GetProcessesByName(current.ProcessName))          {             if (process.Id != current.Id)             {                SetForegroundWindow(process.MainWindowHandle);                break;             }          }       }    } } 
like image 167
Mitchel Sellers Avatar answered Oct 18 '22 18:10

Mitchel Sellers


to force running only one instace of a program in .net (C#) use this code in program.cs file:

public static Process PriorProcess()     // Returns a System.Diagnostics.Process pointing to     // a pre-existing process with the same name as the     // current one, if any; or null if the current process     // is unique.     {         Process curr = Process.GetCurrentProcess();         Process[] procs = Process.GetProcessesByName(curr.ProcessName);         foreach (Process p in procs)         {             if ((p.Id != curr.Id) &&                 (p.MainModule.FileName == curr.MainModule.FileName))                 return p;         }         return null;     } 

and the folowing:

[STAThread]     static void Main()     {         if (PriorProcess() != null)         {              MessageBox.Show("Another instance of the app is already running.");             return;         }         Application.EnableVisualStyles();         Application.SetCompatibleTextRenderingDefault(false);         Application.Run(new Form());     } 
like image 24
snir Avatar answered Oct 18 '22 16:10

snir