カメニッキ

カメとインコと釣りの人です

VB6で同時実行を禁止する

Mutexを使用します。
以下サンプルコードです。

①まず使用する関数の宣言

'CreateMutexの宣言
Private Declare Function CreateMutex Lib "kernel32" ( _
ByVal pSAttr As Long, _
ByVal fOwner As Long, _
ByVal sMutexName As String) As Long

'CloseHandの宣言
Private Declare Function CloseHandle Lib "KERNEL32.DLL" ( _
ByVal hObject As Long _
) As Long
'ReleaseMutexの宣言
Private Declare Function ReleaseMutex Lib "kernel32" (ByVal hMutex As Long) As Long

②実際に使用する(今回のサンプルはあるfunctionの同時起動を禁止)

Private function sample() As String
Dim mutexA As Long
Dim errorCode As Long
'エラー発生時にmutexを閉じる処理をさせるため
On Error Go To errorhandle

'mutexの作成
mutexA = CreateMutex(ByVal 0&, 0&, "このfunctionように何か名前を付ける")
'Err.LastDllErrorの値を取得
errorCode = Err.LastDllError
 'Err.LastDllErrorが183の場合、既に同じ名前でmutexが作成されている
 If errorCode = 183 Then
'エラーの書き出し等
  'mutexを閉じる処理
CloseHandle(mutexA)
'mutexを解放する処理
  ReleaseMutex(mutexA)
Else
'同時起動ではないので通常の処理
End If
Exit function
errorhandle:
'エラーの書き出し等
  'mutexを閉じる処理
CloseHandle(mutexA)
'mutexを解放する処理
  ReleaseMutex(mutexA)
End function

間違いがあればコメントください。