How to Prevent Multiple Instances of a VB Application

ID: Q142937


The information in this article applies to:


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

  1. 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
     


  2. From the File menu, choose Make EXE File.


  3. Exit Visual Basic for Windows.


  4. Start your program through Program Manager or double-click the .EXE file name under Windows File Manager.


  5. Minimize the program you started in step 4.


  6. 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:
  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          : kbcode PrgCtrlsStd 
Version           : 4.00
Platform          : WINDOWS 
Issue type        : 

Last Reviewed: May 26, 1999