Open WinForms - Open Source Windows Forms and Controls

{} - Tips and tricks - C#, ASP.NET
 Subscribe in a reader

Home    Controls    Articles    Contact
  True Single instance application - WinForms.NET
Post comments    Need help?


This article simply explains how you can create a windows application with control on the number of its instances or run only single instance. This is very typical need of a business application. There are already lots of other possible solutions to control this.

e.g. Checking the process list with the name of our application. But this methods don?t seems to be a good approach to follow as everything is decided just on the basis on the application name which may or may not be unique all across.

Another way to use remoting to communicate the application together in order to control the instance but this one is not simple and straight forward approach to solve this problem.

Tip: Webmasters who choose as a base for their website often turn to hosting to improve the performance of their site and ensure glitch free work of all the scripts.

The SingleInstanceController class

This is the main controller class which will take care of application instances. This class needs to be drived from Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase. Add reference of Microsoft.VisualBasic to you project in order to use this class.
using System;
using Microsoft.VisualBasic.ApplicationServices;

namespace Owf
  public class SingleInstanceController
    : WindowsFormsApplicationBase
    public SingleInstanceController()
      // Set whether the application is single instance
      this.IsSingleInstance = true;

      this.StartupNextInstance += new

    void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
      // Here you get the control when any other instance is
      // invoked apart from the first one.
      // You have args here in e.CommandLine.

      // You custom code which should be run on other instances

    protected override void OnCreateMainForm()
      // Instantiate your main application form
      this.MainForm = new Form1();

Now change you main function. Instead of using Application.Run(..) use following
static void Main()
  string[] args = Environment.GetCommand
  SingleInstanceController controller = new SingleInstanceController();

Thats it!

Post comments    Need help?
  Tags: .NET, Single Instance, Windows Application, C#

Facing issue while using? contact

Contact Site Admin: