solitary treeIn Visual Basic, there is a checkbox on the application settings form for “Make single instance application”.  If this checkbox is checked, then subsequent attempts to launch your application are ignored.

If you hit the “View Application Events” button, you can add a function StartupNextInstance, which is called when the user attempts to launch a second instance of your application.

visual basic single instance application

Unfortunately, in C#, there is no intrinsic capability for single-instance applications.  But you can manually add the VB application framework to your C# application.  This framework is contained in Microsoft.VisualBasic.dll, so you will need to add a reference to it to your project.

Next, we need to create a class derived from Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.  This class will replace the “Application” instance normally used by C#.

using Microsoft.VisualBasic.ApplicationServices;

class CSApp : WindowsFormsApplicationBase
{
public CSApp()
{
EnableVisualStyles = true;
IsSingleInstance = true;
}

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

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

// Todo: code here
MessageBox.Show(“Next instance”);
}
}

Then, we have to modify the Main() function of the application to use our class instead of the standard Application instance:

static void Main(string[] commandLine)
{
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
CSApp app = new CSApp();
app.Run(commandLine);
}

The OnStartupNextInstance function will be called by the framework when the user launches a second instance of the application.  This function is called in the “original” instance of the application, not the (temporary) new instance and can be used to access command line parameters and pass them along to your application objects.

Let’s talk tech. Let’s talk programming. Let’s talk about technologies that make your knees quiver. Our eBusiness Solutions team is standing by waiting for your call.

image credit: Solitary Tree

2 Comments

  1. birds

    Its easier to just create a mutex. That also lets you add logic for next instances

  2. Cheatsheet: 2011 04.20 ~ 04.29 - gOODiDEA.NET

    […] Creating a Single-Instance Application in C# […]

Comments are closed.