Skip to content

Commit

Permalink
don't run if an instance is already running
Browse files Browse the repository at this point in the history
  • Loading branch information
ajitid committed Jul 28, 2024
1 parent 970f63b commit 7d3ba6e
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ _Stellate is in usable state but is not finished. That is why I haven't provided

1. Clone this repository
1. Install golang
1. Run `go build -ldflags "-H=windowsgui"` in the project root. A file called stellate.exe will be built.
1. Run `go build -ldflags "-H=windowsgui"` in the project root (this may take few mins to complete). A file called stellate.exe will be built.
1. Open Windows Explorer and copy this file. Then press <kbd>Win</kbd>+<kbd>R</kbd> key and type `shell:startup`. Right click and Paste Shortcut.
1. Double click on this shortcut. The program will run.

Expand Down
4 changes: 4 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ const (
var quit = false // probably ok that it is not protected by a mutex

func main() {
if !checkSingleInstance() {
os.Exit(1)
}

startSystray, stopSystray := systray.RunWithExternalLoop(func() {
iconBytes, err := os.ReadFile("icon.ico")
if err != nil {
Expand Down
42 changes: 42 additions & 0 deletions single-instance_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import (
"fmt"
"syscall"
"unsafe"
)

var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procCreateMutex = kernel32.NewProc("CreateMutexW")
)

// from https://claude.ai/chat/38e56e68-e64a-4a1b-8272-7ac1a5e7ba82
func checkSingleInstance() bool {
mutexName, err := syscall.UTF16PtrFromString("Global\\StellateBrightnessUtilityMutex")
if err != nil {
fmt.Println("Error creating mutex name:", err)
return false
}

handle, _, lastErr := procCreateMutex.Call(
0,
0,
uintptr(unsafe.Pointer(mutexName)),
)

if handle == 0 {
fmt.Println("Error creating mutex:", lastErr)
return false
}

// Check if the mutex already exists
if lastErr == syscall.ERROR_ALREADY_EXISTS {
syscall.CloseHandle(syscall.Handle(handle))
fmt.Println("Another instance is already running")
return false
}

// Keep the mutex handle open until the program exits
return true
}

0 comments on commit 7d3ba6e

Please sign in to comment.