How to Implement a Global Hotkey in Go?

Barbara Streisand
Release: 2024-11-13 00:13:02
Original
404 people have browsed it

How to Implement a Global Hotkey in Go?

Implement a Global Hotkey in Go (golang)

It is possible to create a cross-platform global hotkey using calls to native OS bindings in Go.

Mac

Use addGlobalMonitorForEventsMatchingMask.

Linux

Use XGrabKey.

Windows

Use RegisterHotKey. Here's an example in Go:

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

type Hotkey struct {
    Id        int
    Modifiers int
    KeyCode   int
}

func main() {
    user32 := syscall.MustLoadDLL("user32")
    reghotkey := user32.MustFindProc("RegisterHotKey")
    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, _, _ := 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)
        }
    }
    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)
    }
}
Copy after login

This will register global hotkeys, and the listening loop will print the pressed hotkey to the console. When CTRL ALT X is pressed, the application will exit.

The above is the detailed content of How to Implement a Global Hotkey in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template