Microsoft KB Archive/142937

= How to Prevent Multiple Instances of a VB Application =

Article ID: 142937

Article Last Modified on 1/8/2003

-

APPLIES TO


 * Microsoft Visual Basic 4.0 Professional Edition
 * Microsoft Visual Basic 4.0 16-bit Enterprise Edition

-



This article was previously published under Q142937



SUMMARY
This article describes how to avoid loading a second instance of an application when the user already has one instance running. It also sets the focus to the first instance of the Visual Basic .EXE application when you attempt to start a second instance of the same application.



MORE INFORMATION
With Microsoft Windows applications, you usually want only one instance of each application running at the same time. If, for example, you try to start the Windows File Manager when an instance is already running, the first instance of File Manager is activated and its window is opened. By using the following example, you can achieve the same effect with a Visual Basic application.

Step-by-Step Example
  On the startup form (Form1), put the following code in the Form_Load event: Private Sub Form_Load If App.PrevInstance Then SaveTitle$ = App.Title App.Title = "... duplicate instance." Form1.Caption = "... duplicate instance." AppActivate SaveTitle$ SendKeys "% R", True End End If  End Sub

 From the File menu, choose Make EXE File. Exit Visual Basic for Windows. Start your program through Program Manager or double-click the .EXE file name under Windows File Manager. Minimize the program you started in step 4. Attempt to start another instance of the program by repeating step 4.</ol>

NOTE: If you get an illegal function call error in your program, make sure that you have changed the caption of any currently loaded forms so that their captions are not the same as the application's title.

When you try to launch a second instance of the program, the Visual Basic application executes the following logic:


 * 1) It checks the App object property PrevInstance to see if there is a previous instance of an application with the same App.Title property.
 * 2) If there is, the new instance of the program saves its App.Title property to a local string to be used to activate the first instance of the same name.
 * 3) Then it changes its own name to avoid an ambiguous reference in the AppActivate call.
 * 4) Next, it performs AppActivate, which causes the first instance of the application to be the current window.
 * 5) Now that the first instance of the application has the focus, the second instance uses SendKeys to send the equivalent keystrokes to restore the first instance's window state.
 * 6) Finally, the second instance of the application Ends itself leaving the first instance with the focus.

Additional query words: 4.00 vb4win vb416

Keywords: KB142937

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.