SoFunction
Updated on 2025-03-07

C# implements a method to run only a single instance application (using IsSingleInstance)

From <<Windows Forms 2.0 Programming, 2nd Edition>>   -  Single-Instance Applications, I learned to call IsSingleInstance in order to add a single instance of the application that only runs the application for C# WinForm. It is a good way!

This method is obviously convenient in terms of usability and two methods: Mutex and Process, which run only a single application instance.

Single Instance Concept:

Starting from .NET 2.0, the WindowsFormsApplicationBase class is provided to simplify Windows application programming. It will be strange if you are a developer. The WindowsFormsApplicationBase class is not in the namespace but belongs to the namespace. Perhaps this is a priority benefit as a developer. The corresponding assembly of this class is, but the assembly is included in the .NET framework and if the assembly is to be referenced, there are no additional operations on the deployment.

The WindowsFormsApplicationBase class implements some functions similar to the Application class, but this class also contains some interfaces that simplify the development of Windows Forms application. Let's take a brief look at it below. The WindowsFormsApplicationBase class implements support for single-instance applications. It can be implemented concisely by setting the IsSingleInstance property to True and rewriting the OnStartupNextInstance method.

accomplish

In the - Main method
1. DLL referenced in the project – ,
:

Copy the codeThe code is as follows:
using ;

2. Add a class to

:

Copy the codeThe code is as follows:

public sealed class SingleInstanceApplication : WindowsFormsApplicationBase
{
    public SingleInstanceApplication()
    {
        = true;
        = ;
    }

    protected override void OnCreateMainForm()
    {
        = new MainForm();
    }

    protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)
    {
        (e);
        ();
    }
}

3. Modify the original (new MainForm()); method:

Copy the codeThe code is as follows:

//Add a single-process program
SingleInstanceApplication application = new SingleInstanceApplication();
(args);

The SingleInstanceApplication class inherits from WindowsFormsApplicationBase, is set to single instance mode in the constructor, and is also set to exit the application after the main form is closed. In the inheritance class, the OnCreateMainForm method is rewritten to create the main form. If you want to ensure that a single instance of the application runs, you also need to rewrite the OnStartupNextInstance method. When the next application instance of the application is started, the OnStartupNextInstance method will be executed. In the above implementation code, the base class method is called and the main window is activated.