Results 1 to 5 of 5

Thread: Classic VB - How can I allow only one instance of my application to run at a time?

Threaded View

  1. #1

    Thread Starter
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,127

    Classic VB - How can I allow only one instance of my application to run at a time?

    Method 1: You can read the PrevInstance property of the App object, if the value of this is True then another instance of the application is already running.

    If your program starts with Sub Main, you can use this code to exit the program if another copy is already running:
    VB Code:
    1. 'in sub main...
    2. If App.PrevInstance = True Then
    3.     MsgBox "Already running...."
    4.     Exit Sub
    5. End If
    For forms you need an extra piece of code to also close the form, the following code should be placed in Form_load:
    VB Code:
    1. 'in form_load...
    2. If App.PrevInstance = True Then
    3.     MsgBox "Already running...."
    4.     Unload Me
    5.     Exit Sub
    6. End If

    Method 2: You can use the FindWindow API to search for open windows with your form caption.

    Note that for this to work you must know the exact title to find, so if you change your window title within your program

    (such as adding a file name, like Notepad does) then this will fail. Also, if other running programs have the same caption,

    your program may not run at all.
    VB Code:
    1. Option Explicit
    2.  
    3. Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As
    4.  
    5. String) As Long
    6.  
    7. Public Sub Main()
    8.     Dim m_hWnd As Long
    9.  
    10.     'Change Form1 to your form Caption.
    11.     m_hWnd = FindWindow(vbNullString, "Form1")
    12.     If m_hWnd > 0 Then
    13.         MsgBox "Program " & App.Title & " is already running..."
    14.         Exit Sub
    15.     End If
    16.  
    17.     'Change Form1 to your form name.
    18.     Form1.Show
    19. End Sub
    Last edited by si_the_geek; Aug 21st, 2005 at 09:35 AM. Reason: added explanation & tidied up

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width