c# – How to prevent an application from running multiple times?

Question:

I would like to know how to avoid that when my desktop application is run it can be re-run, that is, have 2 running instances of my application.

Thanks!

Answer:

Using Mutex is another option

bool nuevaInstancia;
using (Mutex mutex = new Mutex(true, Process.GetCurrentProcess().ProcessName, out nuevaInstancia ))
{
   if (nuevaInstancia )
   {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new MainForm());
  }
}

You could also in case it is already running show the window of the current instance through SetForegroundWindow of the user32.dll

Scroll to Top