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.