May 23, 2012

[How to] Single Instance of Application

This article is NOT talking about Singleton Pattern, 
which is a design pattern that keep a class have only one instance.
We're going to make an application have only one instance in the OS.


In VB.Net, you just need to open project property page and check "Single Instance".
However, there's no this option in C#.


We may observe some VB.Net auto generated codes, such as "Application.Designer.vb",
and we'll find out that there're some codes like these:


Public Sub New()
  MyBase.New(AuthenticationMode.Windows)
  Me.IsSingleInstance = true
  Me.EnableVisualStyles = true
  Me.SaveMySettingsOnExit = true
  Me.ShutDownStyle = ShutdownMode.AfterMainFormCloses
End Sub


That is. We just need to rewrite it according C#'s style.

Unfortunately, VB allows Program inherits WindowsFormsApplicationBase and make an instance.
But it not suitable in C#, you should only use static void Main as an entry point.
In other words, we can't let a program inherit it and set this.IsSingleInstance = true.
Therefore, we need a "bridge class" to do all these above for us.


using Microsoft.VisualBasic.ApplicationServices;

static class Program{
  [STAThread]
  static void Main(string[] z){
    InternalProgram program = new InternalProgram();
    program.Run(z);
  }
  private class InternalProgram : WindowsFormsApplicationBase{
    public InternalProgram(){
      this.IsSingleInstance = true;
    }
    protected override void OnCreateMainForm(){
      this.MainForm = new UI();
    }
  }
}


Notice that you must pass command line parameters to internal program.

No comments:

Post a Comment