Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / C# 5.0
Tip/Trick

A C# Single Application Instance Class

Rate me:
Please Sign up or sign in to vote.
4.66/5 (16 votes)
15 Apr 2015CPOL 23.3K   480   33   4
An easy-to-use class to prevent multiple instances of your application from opening and focusing/activating the first instance window.

Introduction

There are different ways to prevent an application from running more than once. This SingleProcessInstance class solves the problem with minimal effort for the programmer.

Background

This tip is based on the article "C# Single Instance App With the Ability To Restore From System Tray (Using Mutex)". If the application is minimized and a second instance is started, the main form of the first instance will be shown and the second instance will terminate silently.

Using the Code

To use the class, just modify the Main() function like this:

C#
static void Main(string[] args)
{
    SingleProcessInstance.RunMain(args, (_args) =>
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    });
}

Optionally, you can define what should happen if the application was started a second time:

C#
static void Main(string[] args)
{
    SingleProcessInstance.RunMain(args, (_args) =>
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }, () =>
    {
        SingleProcessInstance.BringMainFormToFront();
        MessageBox.Show("this application can only be runned in a single instance");
    });
}

History

  • 2015-03-09 First upload

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWPF Version Pin
Patrick Blackman16-Apr-15 13:42
professionalPatrick Blackman16-Apr-15 13:42 
Is there a wpf version of this available or can you convert it to wpf?

GeneralMy vote of 5 Pin
Franc Morales16-Apr-15 10:48
Franc Morales16-Apr-15 10:48 
QuestionThats what i like to see Pin
Dr Gadgit16-Apr-15 9:02
Dr Gadgit16-Apr-15 9:02 
QuestionNice Trick... Pin
Suvabrata Roy15-Apr-15 22:52
professionalSuvabrata Roy15-Apr-15 22:52 

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.