Posts Tagged ‘winforms’

Single instance application with C#

Friday, April 24th, 2009

If you’re developing a winforms application with VB.NET you can set a checkbox in the designer to have a single instance application. This option is not available to C# developers but since language does not matter in the .NET space you can just use the same classes the VB.NET designer uses.

By subclassing WindowsFormsApplicationBase you can get the same behaviour. The class can be found in the Microsoft.VisualBasic.ApplicationServices namespace.

public class SingleInstanceManager
      : WindowsFormsApplicationBase
{
 
    public SingleInstanceManager()
    {
        IsSingleInstance = true;
        EnableVisualStyles = true;
        ShutdownStyle = ShutdownMode.AfterMainFormCloses;
    }
 
    protected override bool OnStartup(StartupEventArgs e)
    {
        return true;
    }
 
    protected override void OnCreateMainForm()
    {
        base.OnCreateMainForm();
        MainForm = new MainForm();
        HideSplashScreen();
    }
 
    protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
    {
        base.OnStartupNextInstance(eventArgs);
        MainForm.Focus();
    }
 
    protected override void OnCreateSplashScreen()
    {
        base.OnCreateSplashScreen();
        SplashScreen = new SplashForm();
    }
}

Change your Program.cs to use this new class.

[STAThread]
static void Main()
{
    var manager = new SingleInstanceManager();
    manager.Run(new string[]{});
}