The Single Instance Application.

Often, it's necessary to ensure that only a single instance of an application is running and if the user tries to run a second copy of the application, the existing instance should show itself instead of hiding behind whatever other windows are open.

Windows Forms applications usually run from a Main method in the C# source or supplied behind the scenes by Visual Basic. The Main method creates an instance of the main form and passes this to the Application.Run method. By intervening at this point, it's possible to ascertain whether a copy of the application is already running and to switch to it instead of running a new form.

Detecting the applications that are already running is accomplished with the Process class and switching to another application can be accomplished by using the ShowWindowAsync API via interop.

The code in the following listings shows this process in VB.NET and in C#.

Public Enum ShowWindowConstants

  SW_HIDE = 0

  SW_SHOWNORMAL = 1

  SW_NORMAL = 1

  SW_SHOWMINIMIZED = 2

  SW_SHOWMAXIMIZED = 3

  SW_MAXIMIZE = 3

  SW_SHOWNOACTIVATE = 4

  SW_SHOW = 5

  SW_MINIMIZE = 6

  SW_SHOWMINNOACTIVE = 7

  SW_SHOWNA = 8

  SW_RESTORE = 9

  SW_SHOWDEFAULT = 10

  SW_FORCEMINIMIZE = 11

  SW_MAX = 11

End Enum

 

  <DllImport("User32.dll")> _

  Public Shared Function ShowWindowAsync(ByVal hWnd As IntPtr, ByVal swCommand As Integer) As Integer

  End Function

 

  <STAThread()> _

  Public Shared Sub Main()

    Dim RunningProcesses As Process() = Process.GetProcessesByName("SingletonApp")

    ‘Change the name above to suit your application

 

    If (RunningProcesses.Length = 1) Then

      Application.Run(New Form1)

    Else

      ShowWindowAsync(RunningProcesses(0).MainWindowHandle, ShowWindowConstants.SW_SHOWMINIMIZED)

      ShowWindowAsync(RunningProcesses(0).MainWindowHandle, ShowWindowConstants.SW_RESTORE)

    End If

 

  End Sub

 

The C# listing defines the same show-window constants so they are omitted for brevity

  [DllImport("User32.dll")]

  public static extern int ShowWindowAsync(IntPtr hWnd , int swCommand);

 

  [STAThread()]

  public static void Main()

  {

    Process[] RunningProcesses = Process.GetProcessesByName("SingletonApp")

    //Change the name above to suit your application

 

    if(RunningProcesses.Length == 1)

      Application.Run(New Form1())

    else

    {

      ShowWindowAsync(RunningProcesses[0].MainWindowHandle, ShowWindowConstants.SW_SHOWMINIMIZED)

      ShowWindowAsync(RunningProcesses[0].MainWindowHandle, ShowWindowConstants.SW_RESTORE)

    }

  }

Return to Tips and Tricks

Go to the GDI+ FAQ

Copyright Robert W. Powell 2003. All rights reserved.