In order to allow only a single instance of an application running I'm using mutex. The code is given below. Is this the right way to do it? Are there any flaws in the code?
How to show the already running application when user tries to open the application the second time. At present (in the code below), I'm just displaying a message that another instance is already running.
static void Main(string[] args) { Mutex _mut = null; try { _mut = Mutex.OpenExisting(AppDomain.CurrentDomain.FriendlyName); } catch { //handler to be written } if (_mut == null) { _mut = new Mutex(false, AppDomain.CurrentDomain.FriendlyName); } else { _mut.Close(); MessageBox.Show("Instance already running"); } }
Console ApplicationWhen we run the application, a Mutex object with a unique identifier (the appName in this case) is created. The constructor takes 3 arguments, with the 3rd being the most important. This output parameter simply tells us whether other objects with the same identifier was already created.
" This feature is already built in to Windows Forms. Just go to the project properties and click the "Single Instance Application" checkbox. "
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.
I did it this way once, I hope it helps:
bool createdNew; Mutex m = new Mutex(true, "myApp", out createdNew); if (!createdNew) { // myApp is already running... MessageBox.Show("myApp is already running!", "Multiple Instances"); return; }
static void Main() { using(Mutex mutex = new Mutex(false, @"Global\" + appGuid)) { if(!mutex.WaitOne(0, false)) { MessageBox.Show("Instance already running"); return; } GC.Collect(); Application.Run(new Form1()); } }
Source : http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx
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