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?
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.
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.
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; }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With