在VBA中创建和使用命名的互斥锁

wpf*_*abe 2 excel vba excel-vba word-vba

我正在WordExcelVBA 做一些交错的剪贴板魔术,我认为剪贴板是一种共享资源,可能应该由一个简单的互斥体来保护。

我将如何在VBA中创建和释放命名互斥体?我找不到与VBA相关的任何内容。好像没有人从VBA创建互斥锁。不可能吗

A.S*_*S.H 5

该答案应该为您提供一种通用方法,该方法使用互斥锁保护某些共享数据,从而实现Excel-VBA和word-VBA之间的同步。详细信息取决于您的目标应用程序。

想法是这样的,您可以在ThisWorkbookExcel 模块中以及类似地在ThisDocumentWord中创建以下代码:

' Module ThisWorkbook or similarly ThisDocument

Private myMutex As Long

Private Const ERROR_ALREADY_EXISTS = 183&
Private Const MUTEX_ALL_ACCESS = &H1F0001

Private Declare PtrSafe Function CreateMutex Lib "kernel32" Alias "CreateMutexA" (ByVal lpMutexAttributes As Long, ByVal bInitialOwner As Long, ByVal lpName As String) As Long
Private Declare PtrSafe Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare PtrSafe Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare PtrSafe Function OpenMutex Lib "kernel32" Alias "OpenMutexA" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal lpName As String) As Long
Private Declare PtrSafe Function ReleaseMutex Lib "kernel32" (ByVal hMutex As Long) As Long

Private Sub Workbook_Open()
    myMutex = CreateMutex(0, 1, "myMutex")
    Dim er As Long: er = Err.LastDllError
    If er = 0 Then
        MsgBox "myMutex Created"
    ElseIf er = ERROR_ALREADY_EXISTS Then
        MsgBox "mutex previously created"
        myMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, "myMutex")
    Else
        MsgBox "mutex creation failed"
    End If
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    CloseHandle myMutex
End Sub

Private Sub doSomeCriticalTask()
    WaitForSingleObject myMutex, 20000 ' say we can wait for 20 seconds
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' do critical section code, access shared data safely
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ReleaseMutex myMutex
End Sub
Run Code Online (Sandbox Code Playgroud)