VB and VBA Users Source Code: Checking to see if an application is already running
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Checking to see if an application is already running
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Wednesday, March 14, 2001
Hits:
1802
Category:
Windows API
Article:
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 ReleaseMutex Lib "kernel32" (ByVal hMutex As Long) 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 : sApplicationId A unique string which will identify your application. ' [bAppTerminating] 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. 'Author : Andrew Baker 'Date : 03/09/2000 13:58 'Notes : In VB 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(sApplicationId As String, Optional bAppTerminating As Boolean = False) As Boolean Static slhwndMutex As Long Const ERROR_ALREADY_EXISTS = 183& If bAppTerminating = True And CBool(slhwndMutex) = True Then 'Release and close the Mutex object. ReleaseMutex slhwndMutex CloseHandle slhwndMutex slhwndMutex = 0 ElseIf slhwndMutex <> 0 Then 'This is the only copy of the application running AppExists = False Else 'Attempt to create a Mutex object slhwndMutex = CreateMutex(ByVal 0&, 1, sApplicationId) If (Err.LastDllError = ERROR_ALREADY_EXISTS) Then 'Failed to create Mutex object, another copy 'of the application must already be open CloseHandle slhwndMutex slhwndMutex = 0 AppExists = True Else AppExists = False End If End If End Function
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder