Running a Single Instance on an Application - September 2009

The tip-of-the-month demonstrates running only one instance of a Windows application. Much of this code was developed by Bob Powell. Click here to link to Bob's site. He created VB and C# samples. I modified the VB code for use in an application. Bob's code runs 'inline' with the application. I modified the code to run in a code module. Today I further modified the code and placed it in a class module. This text is copied from Bob's web site:

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 other open windows. 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.

To show how the code works I created a demo application. I also added an overloaded method to optionally NOT activate the application.

The Demo


Only one instance of this application is loaded.
The initial load time and activated time is displayed.
In this demo the application is activated again 55 seconds later [07:19:26 - 07:18:31]

The demo uses code contained in class cSingleInstance.vb. Although not used in the demo, similar code is also distributed in modSingleInstance.vb. Your can chose the version to include in your application.

cSingleInstance Method

Method Operands Description
ApplicationRunningAlready [bActivate As Boolean] Test if the application is already running.
If bActivate is True then activate the prior instance.
Default is True.

Sample Calling Code

Dim o As New cSingleInstance
If o.ApplicationRunningAlready() Then

Caveat Lector

The prior instance of the application is not always activated. I did not spend a lot of time trying to figure out why. If you can then let me know. The method ApplicationRunningAlready test does always work.

Download VB.Net Code

Download - VS2005 VB.Net Zipped File  Size 
Single Instance SingleInstance.zip 21k

Previous Tip   Tip Index    Next Tip

Home

Updated 2011/04/16