65.9K
CodeProject is changing. Read more.
Home

Run Only One Copy Of Application

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.44/5 (9 votes)

Mar 18, 2011

CPOL
viewsIcon

31692

Run Only One Copy Of Application

This is a class to make an application where only one instance of app can be run at a time in C#. The method must be called in Program.cs by replacing:
Application.Run(new Form1());
with
Chico.SingleApp.Initialize(true, new Form1());
a shorter version(where this initial code originated from) was posted by: Ron Whittle and can be found at http://www.daniweb.com/software-development/csharp/code/352511[^]
using System;
using System.Threading;
using System.Windows.Forms;
namespace Chico
{
    public class SingleApp
    {
        private static Boolean IsSingleAppMode;
        private static Mutex singleApp;
        private const Int32 waitTime = 3000;
        public static Boolean Initialize(Boolean value, Form form)
        {
            try
            {
                if (value)
                {
                    using (singleApp = InitializeSingleAppMode(IsSingleAppMode))
                    {
                        if (StartAsSingleAppMode(IsSingleAppMode))
                        {
                            StartApplication(form);
                        }
                    }
                }
                else
                {
                    StartApplication(form);
                }
            }
            catch { }
            return value;
        }
        private static Boolean StartAsSingleAppMode(Boolean result)
        {
            return singleApp.WaitOne(waitTime, result);
        }
        private static void StartApplication(Form mainForm)
        {
            Application.Run(mainForm);
        }
        private static Mutex InitializeSingleAppMode(Boolean result)
        {
            return new Mutex(result, "anydomain.com myprogramname", out IsSingleAppMode);
        }
    }
}
If you like the code or plan to use the code, please vote for me and stop by http://www.daniweb.com/software-development/csharp/code/352511[^] and take a look at the original code by Ron Whittle. Thanks and hope you like the code.