VB3 How to Prevent Multiple Instances of a VB Application
ID: Q102480
|
The information in this article applies to:
-
Microsoft Visual Basic Standard and Professional Editions for Windows, version 3.0
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:
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.
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:
- It checks the App object property PrevInstance to see if there is a
previous instance of an application with the same App.Title property.
- 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.
- Then it changes its own name to avoid an ambiguous reference in the
AppActivate call.
- Next, it performs AppActivate, which causes the first instance of the
application to be the current window.
- 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.
- Finally, the second instance of the application Ends itself leaving the
first instance with the focus.
Additional query words:
2.00 3.00
Keywords : kbcode PrgCtrlsStd
Version : 2.00 3.00
Platform : WINDOWS
Issue type :
|