dee-u
May 31st, 2005, 01:34 AM
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:'in sub main...
If App.PrevInstance = True Then
MsgBox "Already running...."
Exit Sub
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:'in form_load...
If App.PrevInstance = True Then
MsgBox "Already running...."
Unload Me
Exit Sub
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.
Option Explicit
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As
String) As Long
Public Sub Main()
Dim m_hWnd As Long
'Change Form1 to your form Caption.
m_hWnd = FindWindow(vbNullString, "Form1")
If m_hWnd > 0 Then
MsgBox "Program " & App.Title & " is already running..."
Exit Sub
End If
'Change Form1 to your form name.
Form1.Show
End Sub
If your program starts with Sub Main, you can use this code to exit the program if another copy is already running:'in sub main...
If App.PrevInstance = True Then
MsgBox "Already running...."
Exit Sub
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:'in form_load...
If App.PrevInstance = True Then
MsgBox "Already running...."
Unload Me
Exit Sub
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.
Option Explicit
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As
String) As Long
Public Sub Main()
Dim m_hWnd As Long
'Change Form1 to your form Caption.
m_hWnd = FindWindow(vbNullString, "Form1")
If m_hWnd > 0 Then
MsgBox "Program " & App.Title & " is already running..."
Exit Sub
End If
'Change Form1 to your form name.
Form1.Show
End Sub