Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent launching my app multiple times?

I deployed my C# WinForms application using ClickOnce installation. Everything works fine with it (after a lot of work) :), but now I'm facing a problem:

Whenever I click on the application shortcut in the Start menu, a new instance starts. I need to avoid this.

What can I do to prevent multiple launches?

like image 890
Tolga Evcimen Avatar asked Feb 27 '13 14:02

Tolga Evcimen


People also ask

What is single instance application?

A Single Instance application is an application that limits the program to run only one instance at a time. This means that you cannot open the same program twice.

How can avoid multiple instances of Windows form in C#?

What you can do is to make the constructor of the Form class private, so nobody can accidentally create one of these. Then call in reflection, convert the ctor to public and make sure you create one and only one instance of it.


2 Answers

At program startup check if same process is already running:

using System.Diagnostics;  static void Main(string[] args) {    String thisprocessname = Process.GetCurrentProcess().ProcessName;     if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)       return;            } 
like image 157
semao Avatar answered Oct 02 '22 13:10

semao


Use this code:

[STAThread] static void Main()  {    using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))    {       if(!mutex.WaitOne(0, false))       {          MessageBox.Show("Instance already running");          return;       }        Application.Run(new Form1());    } } 

from The Misunderstood Mutex

like image 33
MikroDel Avatar answered Oct 02 '22 14:10

MikroDel