golang-design / hotkey

⌨️ cross-platform hotkey package
https://golang.design/x/hotkey
MIT License
215 stars 10 forks source link

Hotkey shortcut monitoring will hijack information #26

Open Esword618 opened 1 year ago

Esword618 commented 1 year ago

Hotkey shortcut monitoring will hijack the information of the shortcut key. When I run the following code, I copy a piece of text and paste it in the browser's search box. The information is hijacked, and it can only be paused when I end the program.

package main

import (
    "golang.design/x/clipboard"
    "log"
    "sync"

    "golang.design/x/hotkey"
    "golang.design/x/hotkey/mainthread"
)

func main() {
    mainthread.Init(fn)
}

func fn() {
    err := clipboard.Init()
    if err != nil {
        panic(err)
    }
    wg := sync.WaitGroup{}
    wg.Add(2)
    go func() {
        defer wg.Done()
        for {
            err := listenHotkey(hotkey.KeyC, hotkey.ModCtrl)
            if err != nil {
                log.Println(err)
            }
        }
    }()
    go func() {
        defer wg.Done()
        for {
            err := listenHotkey(hotkey.KeyV, hotkey.ModCtrl)
            if err != nil {
                log.Println(err)
            }
            //imageData := clipboard.Read(clipboard.FmtImage)
            //base64String := base64.StdEncoding.EncodeToString(imageData)
            //log.Println(base64String)
            textData := clipboard.Read(clipboard.FmtText)
            log.Println(string(textData))
        }
    }()
    wg.Wait()
}

func listenHotkey(key hotkey.Key, mods ...hotkey.Modifier) (err error) {
    var ms []hotkey.Modifier
    ms = append(ms, mods...)
    hk := hotkey.New(ms, key)

    err = hk.Register()
    if err != nil {
        return
    }

    <-hk.Keydown()
    log.Printf("hotkey: %v is down\n", hk)
    <-hk.Keyup()
    log.Printf("hotkey: %v is up\n", hk)
    hk.Unregister()
    return
}