Source

VB and VBA Code Library / clsMutex.cls

Full commit
VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
  Persistable = 0  'NotPersistable
  DataBindingBehavior = 0  'vbNone
  DataSourceBehavior  = 0  'vbNone
  MTSTransactionMode  = 0  'NotAnMTSObject
END
Attribute VB_Name = "clsMutex"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
''
' Manage an Application Mutex for the current application
'
' @remarks  Mutex name = App.Title
' @author   Christoph Juengling <christoph@juengling-edv.de>
' @link   https://bitbucket.org/juengling/vb-and-vba-code-library
'
Option Explicit

Private Declare Function CreateMutex Lib "kernel32.dll" Alias "CreateMutexA" (lpMutexAttributes As Any, ByVal bInitialOwner As Long, ByVal lpName As String) As Long
Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long
Private Declare Function ReleaseMutex Lib "kernel32" (ByVal hMutex As Long) As Long

Private m_lMutexHandle As Long

Private Sub Class_Initialize()

m_lMutexHandle = 0
Create

End Sub

Private Sub Class_Terminate()

Release

End Sub

''
' Create the Mutex
'
Public Sub Create()

m_lMutexHandle = CreateMutex(ByVal CLng(0), CLng(1), App.title)

End Sub

''
' Release the Mutex and close handle
'
Public Sub Release()

If m_lMutexHandle > 0 Then
    ReleaseMutex m_lMutexHandle
    CloseHandle m_lMutexHandle
    m_lMutexHandle = 0
End If

End Sub