Single application instance

I needed my app to be a single-instance app. It was easy to implement, like so:

bool mutexIsNew;
Mutex mutex = new Mutex(true, "SomeUniqueID", out mutexIsNew);
if (mutexIsNew)
Application.Run(new MainForm());

A problem arose though when my app started to need to receive command line arguments. How do you also pass those onto the original app? There is a class for this purpose named
“WindowsFormsApplicationBase”, it’s in Microsoft.VisualBasic.dll

01: Add a class to your project like so:

internal class SingleInstanceApplication : WindowsFormsApplicationBase
{
private MainForm MainFormInstance;
internal SingleInstanceApplication()
{
IsSingleInstance = true;
EnableVisualStyles = true;
MainFormInstance = new MainForm();
MainForm = MainFormInstance;
}

protected override bool OnStartup(StartupEventArgs eventArgs)
{
return base.OnStartup(eventArgs);
MainFormInstance.AcceptCommandArguments(eventArgs.CommandLine);
}

protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
base.OnStartupNextInstance(eventArgs);
MainFormInstance.AcceptCommandArguments(eventArgs.CommandLine);
}
}

02: Add a method to your MainForm class like so:

internal void AcceptCommandArguments(IList args)
{
}

03: Finally change your project source code like so:

[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SingleInstanceApplication singleInstanceApplication = new SingleInstanceApplication();
singleInstanceApplication.Run(args);
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *