Multiple Instances
Users may try to run an application multiple times. This is not always desirable because it can cause problems if the application is not prepared to handle this condition. For example, global instance data can become corrupt if an application is started multiple times.
Handling Multiple Instances
There are two ways to prevent problems associated with multiple instances:
- An application can refuse to start a second instance if a first instance is detected .
- The application can anticipate multiple instances and handle tasks such as initialization appropriately.
In either case, first you will need to test for multiple instances in your application's startup code.
Running multiple instances is not always undesirable. For example, if an application allows users to run several instances, it can allow communication among its different instances.
Testing for Multiple Instances
One way to detect multiple instances is to call the Visual Basic
FindWindow function when your application first starts. This function looks to see whether an instance of the application is already running. This method works most of the time, but is not the most effective. If the user tries to run the application twice in rapid succession,
FindWindow may incorrectly indicate that the application has not started.
One option is to use the PrevInstance property of the App object. This determines whether a previous instance of the application is already running.
Example
In this example, Visual Basic uses the
Load event to check whether a previous version is running:
Private Sub Form_Load() ' Check to see if this app is already running If App.PrevInstance = True Then MsgBox "A previous instance of this application" & _ "is already running.", vbCritical, "MyApp" End End If End Sub
* To test for another instance of a program in Visual Basic
- Start Visual Basic and create a new standard EXE project.
- Double-click on Form1 to open the code window.
- In the Load event procedure, type the following code:
Private Sub Form_Load() If App.PrevInstance Then MsgBox "This program is already running." Unload Me End If End Sub
- From the Project menu, click Project1 Properties .
- Change the Project Name to "Instance", then click OK .
- From the File menu, click Make Instance.exe .
- Browse to the directory where you created the Instance.exe file in Windows Explorer and double-click on it to run the program.
The program executes and Form1 displays.
- Double-click on the Instance.exe file in Windows Explorer to run a second instance of the program.
The message box that you created in Visual Basic is now displayed to notify you that an instance of the application is already running.
- Click OK to close the message box, then close the first instance of the Instance.exe program.