Visual Basic Programming Code Examples Visual Basic > Windows and Controls Code Examples Checking to see if an application is already running Checking to see if an application is already running In VBA there is no easy way to determine if your application has already been opened. In VB the App.Previous instance will return False is the application has not fully initialised. So the user can open several instances of the application while it is initialising. The following functions overcomes these short falls. Option Explicit Private Declare Function CreateMutex Lib "kernel32" Alias "CreateMutexA" (ByVal lpMutexAttributes As Long, ByVal bInitialOwner As Long, ByVal lpName As String) As Long Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long 'Purpose : Tests to see if another copy of the application is already running. 'Inputs : sApplicationTitle A unique string which will identify your application. ' [bAppTerminated] If True the Mutex object which signifys the application is ' running will be will be destroyed. 'Outputs : Returns True if the application is already running. 'Notes : App.PrevInstance only returns True once the Application is fully initialised. However, ' this method of checking an application's existance is overcomes this short fall by ' creating an Mutex object which will persist until the application terminates. All other ' instances of the application will error when they try to create this object and hence ' only the first instance of the Application will get a return value of False. ' The Mutex object will be destroyed if your application is unloaded or crashes. 'Revisions : Function AppExists(sApplicationTitle As String, Optional bAppTerminated As Boolean = False) As Boolean Static zlhwndMutex As Long Const ERROR_ALREADY_EXISTS = 183& If IDERunning = True Then 'Have to use this in IDE mode as the Mutex object will 'presist for duration of the VB session. AppExists = App.PrevInstance ElseIf bAppTerminated = True And CBool(zlhwndMutex) = True Then 'Close the Mutex object. CloseHandle zlhwndMutex zlhwndMutex = 0 ElseIf zlhwndMutex Then 'This is the only copy of the application running AppExists = False Else 'Attempt to create a Mutex object zlhwndMutex = CreateMutex(ByVal 0&, 1, sApplicationTitle) If (Err.LastDllError = ERROR_ALREADY_EXISTS) Then 'Failed to create Mutex object, another copy 'of the application must already be open CloseHandle zlhwndMutex zlhwndMutex = 0 AppExists = True Else AppExists = False End If End If End Function 'Purpose : Tests if the VB IDE is running 'Inputs : N/A 'Outputs : Returns True if the IDE is running 'Notes : Since the Debug.Print line will be removed in the compiled application ' the code will execute instantly without error. 'Revisions : 'Assumptions : Function IDERunning() As Boolean On Error GoTo IDERunning Debug.Print 1 / 0 Exit Function IDERunning: On Error GoTo 0 IDERunning = True End Function