Single Instance Windows Forms Application

On a previous post I talked about how to create a splash screen for a windows forms application. Now I will be demonstrating how to make a single instance application.

As in the other post I will be using the WindowsFormsApplicationBase class included with the .NET Framework. In order to use this class your application project must add a reference to Microsoft.VisualBasic library.

Having added the reference, the code needed is very simple:

using System;
using System.Linq;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;

class SingleInstanceApp : WindowsFormsApplicationBase
{
    public SingleInstanceApp()
        : base()
    {
        this.IsSingleInstance = true;
    }

    protected override void OnStartupNextInstance(
        StartupNextInstanceEventArgs e)
    {
        base.OnStartupNextInstance(e);

        string[] secondInstanceArgumens = e.CommandLine.ToArray();

        // Handle command line arguments of second instance

        if (e.BringToForeground)
        {
            this.MainForm.BringToFront();
        }
    }

    protected override void OnCreateMainForm()
    {
        base.OnCreateMainForm();

        this.MainForm = new MainForm();
    }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        new SingleInstanceApp().Run(Environment.GetCommandLineArgs());
    }
}

With this sample code you will have a single instance application that, if configured to do so, will bring itself to the foreground when the user tries to launch a second instance. More advanced scenarios such as handling the command line arguments of the second instance on the first instance are also supported.

Advertisements

3 thoughts on “Single Instance Windows Forms Application”

  1. Hi,

    So much good code in the Visualbasic assembly for even for C# programmers. Have you tried the SingleInstanceApp in Citrix/AppV environent with multiple users running apps?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s