Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Run Only One Copy Of Application

0.00/5 (No votes)
19 Mar 2011 1  
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:

C#
Application.Run(new Form1());


with

C#
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[^]

C#
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here