Click here to Skip to main content
14,980,146 members
Articles / Programming Languages / C# 5.0
Tip/Trick
Posted 15 Apr 2015

Tagged as

Stats

21K views
474 downloads
33 bookmarked

A C# Single Application Instance Class

Rate me:
Please Sign up or sign in to vote.
4.66/5 (16 votes)
15 Apr 2015CPOL
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)

Share

About the Author

sx2008
Software Developer (Senior)
Germany Germany
No Biography provided

Comments and Discussions

 
QuestionWPF Version Pin
Patrick Blackman16-Apr-15 13:42
professionalPatrick Blackman16-Apr-15 13:42 
GeneralMy vote of 5 Pin
Franc Morales16-Apr-15 10:48
MemberFranc Morales16-Apr-15 10:48 
QuestionThats what i like to see Pin
Dr Gadgit16-Apr-15 9:02
MemberDr 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.