How can I tell if my program is already running?
Printable View
How can I tell if my program is already running?
if you want the 2nd program to end if its already running, put this in the form_load
Code:If App.PrevInstance = True Then
End
End If
Put this statement as the first statement in the form load event of your startup form:
Code:If App.PrevInstance Then
MsgBox "My Program is already running." , _
vbExclamation, "Cannot Execute"
End
End If
'from Microsoft Databse
'check for previous instance of app
'
Option Explicit
Private Sub Form_Load()
If App.PrevInstance Then
ActivatePrevInstance
End If
End Sub
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'2) Add a Standard Module to the Project.
'3) Paste the following code into the module:
Option Explicit
Public Const GW_HWNDPREV = 3
Declare Function OpenIcon Lib "user32" (ByVal hwnd As Long) As Long
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
Sub ActivatePrevInstance()
Dim OldTitle As String
Dim PrevHndl As Long
Dim result As Long
'Save the title of the application.
OldTitle = App.Title
'Rename the title of this application so FindWindow
'will not find this application instance.
App.Title = "unwanted instance"
'Attempt to get window handle using VB4 class name.
PrevHndl = FindWindow("ThunderRTMain", OldTitle)
'Check for no success.
If PrevHndl = 0 Then
'Attempt to get window handle using VB5 class name.
PrevHndl = FindWindow("ThunderRT5Main", OldTitle)
End If
'Check if found
If PrevHndl = 0 Then
'Attempt to get window handle using VB6 class name
PrevHndl = FindWindow("ThunderRT6Main", OldTitle)
End If
'Check if found
If PrevHndl = 0 Then
'No previous instance found.
Exit Sub
End If
'Get handle to previous window.
PrevHndl = GetWindow(PrevHndl, GW_HWNDPREV)
'Restore the program.
result = OpenIcon(PrevHndl)
'Activate the application.
result = SetForegroundWindow(PrevHndl)
'End the application.
End
End Sub
The version I pinched of a web site somewhere..
In Form_Load() ...
Code:Dim SaveTitle as string
If App.PrevInstance Then
SaveTitle = App.title
App.title = "... duplicate instance."
Me.Caption = "... duplicate instance."
AppActivate SaveTitle$
SendKeys "% R", True
End
End If
Assume you main program's form is frmMain.frm and just create a Main sub procedure and set it as your program startup object.
Code:Option Explicit
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Private Const SW_SHOWNORMAL = 1
Public Sub Main()
Dim xAppName$
If App.PrevInstance Then
xAppName = "<Your Application Title>"
xhwnd = FindWindow(0&, xAppName)
If xhwnd <> 0 Then
AppActivate xAppName
xhwnd = ShowWindow(xhwnd, SW_SHOWNORMAL)
End
End If
End If
Load frmMain
frmMain.Show
End Sub