Easily Create a Single Instance Windows Application

Hi

Many a time we do not want the user to create the second instance of the (Windows) Application on the same machine. For this we need to restrict the user from opening more than one instance of the application.

The notion of Global and mutex has been introduced by Microsoft to solve this problem. Things like Citrix might fail in condition were you have multi user session (terminal service)

We use the following code to restrict the use of two instance of an application.

  Mutex instanceLock = new Mutex(false, "Name of the Assembly");

            if (instanceLock.WaitOne(0, false))

            {

                try

                {

                    Application.EnableVisualStyles();

                    Application.SetCompatibleTextRenderingDefault(false);

                    Application.Run(new frmMain());

                }

                finally

                { instanceLock.ReleaseMutex(); }

            }

            else

            {

                MessageBox.Show("You cannot have two instance of this application running");

                Application.Exit();

            }

[Note: the mutex class is in System.Threading class]

Hope this helps
Thanks
Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 4/28/2007 10:31:17 AM

Thanks

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia