Click here to Skip to main content
15,885,870 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

Run Only One Copy Of Application

Rate me:
Please Sign up or sign in to vote.
4.44/5 (10 votes)
19 Mar 2011CPOL 31.4K   40   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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I do not claim to be wrong! I just rarely ever write.

Comments and Discussions

 
GeneralNot in C#? Pin
Anshul R25-May-11 20:35
Anshul R25-May-11 20:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.