How to Implement a Cross-Platform Global Hotkey in Go?

Barbara Streisand
Release: 2024-11-08 03:09:02
Original
778 people have browsed it

How to Implement a Cross-Platform Global Hotkey in Go?

Implementing a Global Hotkey in Go

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:

  1. Load User32 DLL: Load the user32.dll library, which contains the necessary functions for hotkey management.
  2. Register Hotkeys: Use the RegisterHotKey function to register hotkeys with specific key combinations.
  3. Handle Key Events: Employ the PeekMessage function to continuously check for and respond to message events. When a hotkey is pressed, its registered ID is stored in the WPARAM field, allowing the application to identify the pressed hotkey.

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)
    }
}
Copy after login

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!

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