Ariver
2026-06-07 c721471f3778334f0cdcfdd3a098e1353652762a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//go:build windows
 
package singleinstance
 
import (
    "fmt"
    "syscall"
    "unsafe"
)
 
var (
    kernel32         = syscall.NewLazyDLL("kernel32.dll")
    procCreateMutex  = kernel32.NewProc("CreateMutexW")
    procReleaseMutex = kernel32.NewProc("ReleaseMutex")
    procCloseHandle  = kernel32.NewProc("CloseHandle")
)
 
const errorAlreadyExists = 183
 
type windowsLock struct {
    handle syscall.Handle
}
 
// Acquire tries to acquire a named mutex. Returns error if another instance holds it.
func Acquire() (Lock, error) {
    name, err := syscall.UTF16PtrFromString("Global\\PrivateVoiceInputSingleInstance")
    if err != nil {
        return nil, err
    }
 
    handle, _, err := procCreateMutex.Call(0, 0, uintptr(unsafe.Pointer(name)))
    if handle == 0 {
        return nil, fmt.Errorf("CreateMutex failed: %v", err)
    }
 
    if err.(syscall.Errno) == errorAlreadyExists {
        procCloseHandle.Call(handle)
        return nil, fmt.Errorf("another instance is already running")
    }
 
    return &windowsLock{handle: syscall.Handle(handle)}, nil
}
 
func (l *windowsLock) Release() {
    if l.handle != 0 {
        procReleaseMutex.Call(uintptr(l.handle))
        procCloseHandle.Call(uintptr(l.handle))
        l.handle = 0
    }
}