Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#5.0

A C# Single Application Instance Class

4.66/5 (16 votes)
15 Apr 2015CPOL 23.9K   480  
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)