Home >Backend Development >Golang >How can I implement global hotkeys in Go across multiple operating systems, including Windows?

How can I implement global hotkeys in Go across multiple operating systems, including Windows?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 13:30:02743browse

How can I implement global hotkeys in Go across multiple operating systems, including Windows?

Implementing Global Hotkeys in Go

While there are limited cross-platform library options for implementing global hotkeys in Go, it is possible using system calls through the syscall package. Here's how you can achieve this on multiple operating systems, including Windows.

Windows

To register hotkeys in Windows, we utilize the user32.dll library and its RegisterHotkey() function. Here's a complete example:

const (
    ModAlt = 1 << iota
    ModCtrl
    ModShift
    ModWin
)

type Hotkey struct {
    Id        int
    Modifiers int
    KeyCode   int
}

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)
}

func main() {
    user32 := syscall.MustLoadDLL("user32")
    reghotkey := user32.MustFindProc("RegisterHotKey")
    defer user32.Release()

    keys := map[int16]*Hotkey{
        1: &Hotkey{1, ModAlt + ModCtrl, 'O'},
        2: &Hotkey{2, ModAlt + ModShift, 'M'},
        3: &Hotkey{3, ModAlt + ModCtrl, '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 := user32.MustFindProc("PeekMessageW")
        peekmsg.Call(uintptr(unsafe.Pointer(msg)), 0, 0, 0, 1)

        if id := msg.WPARAM; id != 0 {
            fmt.Println("Hotkey pressed:", keys[id])
            if id == 3 {
                fmt.Println("CTRL+ALT+X pressed, goodbye...")
                return
            }
        }

        time.Sleep(time.Millisecond * 50)
    }
}

The above is the detailed content of How can I implement global hotkeys in Go across multiple operating systems, including Windows?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn