Monday, February 11, 2013

Single Instace of an Application

Hi guys most of cases we don't want to make multiple instants of applications to be executed in single machine, I am providing a code span to prevent this problem as follows...

In most of the window based applications code looks like this...


[STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMainForm());
        }


Now I am made some changes in above code it looks like this....


[STAThread]
        static void Main()
        {
            //Make Single Instace of an Application I am using Mutex
            bool createdNew;
            using (new System.Threading.Mutex(false, "SingleWindow", out createdNew))
            {
                if (createdNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new frmMainForm());
                }
            }
        }

Here "SingleWindow" is the name of exe or project name that I am making and System.Threading.Mutex function updates value of boolean veriable createdNew true if no exe is running in the machine named "SingleWindow". So, code is self explanatory that what I have done...

No comments:

Post a Comment

Age Calculator - Calculating difference between dates

Dear friends in most of the cases you need to work on dates. I had been stuck while calculating exact age of a person or total experience i...