C implements the method of running only a single instance application (IsSingleInstance using ES1en.Net)

  • 2020-06-19 11:39:40
  • OfStack

from < < Windows Forms 2.0 Programming, 2nd Edition > > In chapter 1, you learned to call IsSingleInstance in VB.Net to add a single instance of C# WinForm (Single Instance Application) running only the application.

This approach is obviously easier to use than Mutex and Process, which only run a single application instance.

Single Instance Concept:

Starting with.NET 2.0, WindowsFormsApplicationBase classes have been provided to simplify Windows application programming, and if you are a developer you may be surprised that the WindowsFormsApplicationBase class is not in the ES31en.Windows.Forms namespace but in the ES34en.VisualBasic.ApplicationServices namespace, perhaps as a priority for VB.NET developers. The assembly corresponding to this class is ES39en.VisualBasic.dll, but the assembly is included in the.NET framework from 1 to 1, and there are no additional operations on the deployment if the assembly is to be referenced.

The WindowsFormsApplicationBase class implements a number of features similar to the Application class, but it also contains an interface that simplifies Windows Forms application development. The WindowsFormsApplicationBase class implements support for single-instance applications and can be implemented concisely by setting the IsSingleInstance attribute to True and overriding the OnStartupNextInstance method.

implementation

In the ES57en. cs-ES59en method
DLL?? Microsoft. VisualBasic. DLL??
Program.cs:

using Microsoft.VisualBasic.ApplicationServices;

2. Add a class to ES73en.cs

Program.cs:


public sealed class SingleInstanceApplication : WindowsFormsApplicationBase
{
    public SingleInstanceApplication()
    {
        base.IsSingleInstance = true;
        base.ShutdownStyle = ShutdownMode.AfterMainFormCloses;
    }     protected override void OnCreateMainForm()
    {
        base.MainForm = new MainForm();
    }     protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)
    {
        base.OnStartupNextInstance(e);
        base.MainForm.Activate();
    }
}

3. Modify the original ES83en. Run(new MainForm()); The method is:


// Add run single process program
SingleInstanceApplication application = new SingleInstanceApplication();
application.Run(args);

The SingleInstanceApplication class, which inherits from WindowsFormsApplicationBase, is set to single-instance mode in the constructor and is set to exit the application when the main form closes. In the inherited class, the OnCreateMainForm method is overridden to create the main form. To ensure that the application runs on a single instance, you need to override the OnStartupNextInstance method, which is executed when the next application instance of the application starts. In the above implementation code, the base class method is called and the main window is activated.


Related articles: