Challenge: Implementing a cross-platform (Mac, Linux, Windows) global hotkey in Go that responds to user input anywhere in the operating system.
Solution:
Utilizing the syscall package, one can access native operating system functions to register and listen for global hotkeys.
For Windows specifically:
Example Application:
A simple Go application that demonstrates hotkey registration and handling on Windows:
package main import ( "fmt" "os" "time" "github.com/gonuts/syscall/՚user32" ) type Hotkey struct { Id int // Unique id Modifiers int // Mask of modifiers KeyCode int // Key code, e.g. 'A' } func (h *Hotkey) String() string { mod := &bytes.Buffer{} if h.Modifiers&ModAlt != 0 { mod.WriteString("Alt+") } if h.Modifiers&ModCtrl != 0 { mod.WriteString("Ctrl+") } if h.Modifiers&ModShift != 0 { mod.WriteString("Shift+") } if h.Modifiers&ModWin != 0 { mod.WriteString("Win+") } return fmt.Sprintf("Hotkey[Id: %d, %s%c]", h.Id, mod, h.KeyCode) } const ( ModAlt = 1 << iota ModCtrl ModShift ModWin ) func main() { user32 := syscall.MustLoadDll("user32") defer user32.Release() reghotkey := user32.MustFindProc("RegisterHotKey") peekmsg := user32.MustFindProc("PeekMessageW") keys := map[int16]*Hotkey{ 1: &Hotkey{1, ModAlt + ModCtrl, 'O'}, // ALT+CTRL+O 2: &Hotkey{2, ModAlt + ModShift, 'M'}, // ALT+SHIFT+M 3: &Hotkey{3, ModAlt + ModCtrl, 'X'}, // ALT+CTRL+X } for _, v := range keys { r1, _, err := reghotkey.Call( 0, uintptr(v.Id), uintptr(v.Modifiers), uintptr(v.KeyCode)) if r1 == 1 { fmt.Println("Registered", v) } else { fmt.Println("Failed to register", v, ", error:", err) } } for { var msg = &MSG{} peekmsg.Call(uintptr(unsafe.Pointer(msg)), 0, 0, 0, 1) // Registered id is in the WPARAM field: if id := msg.WPARAM; id != 0 { fmt.Println("Hotkey pressed:", keys[id]) if id == 3 { // CTRL+ALT+X = Exit fmt.Println("CTRL+ALT+X pressed, goodbye...") os.Exit(0) } } time.Sleep(time.Millisecond * 50) } }
This example provides a complete implementation of hotkey registration and handling on Windows, which can be adapted for other operating systems using similar principles.
The above is the detailed content of How to Implement a Cross-Platform Global Hotkey in Go?. For more information, please follow other related articles on the PHP Chinese website!