pkg/neptune/keyevent.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package neptune

import (
hook "github.com/robotn/gohook"
)

type KeyEvent struct {
Enabled bool
EvChan chan hook.Event
}

type Event interface {
KindCode() uint8
Keycode() uint16
}

type CustomEvent struct {
Kind uint8
Keycodes uint16
}

const (
KeyDown = 3
KeyUp = 5
)

func NewKeyEvent() *KeyEvent {
return &KeyEvent{}
}

func (Kv *KeyEvent) StartEven() chan hook.Event {
Kv.Enabled = true
Kv.EvChan = hook.Start()
return Kv.EvChan
}

func (Kv *KeyEvent) StopEvent() {
if Kv.Enabled {
hook.End()
Kv.Enabled = false
}
}

func (k *KeyEvent) EventChannel() chan hook.Event {
return k.EvChan
}

func (ce CustomEvent) KindCode() uint8 {
return ce.Kind
}

func (ce CustomEvent) Keycode() uint16 {
return ce.Keycodes
}

func (k *KeyEvent) CodeToChar(r uint16) string {
return hook.RawcodetoKeychar(r)
}

Certainly, let me explain the code block you provided:

The code is written in Go and is part of the neptune package. It defines a KeyEvent struct and related functionality for handling keyboard events.

Here’s a breakdown of the key parts:

  1. KeyEvent Struct:

    • Enabled : A boolean flag to track if the key event handling is enabled.
    • EvChan : A channel to receive the keyboard events.
  2. Event Interface:

    • Defines an interface with two methods: KindCode() and Keycode() , which are used to get the kind and keycode of an event.
  3. CustomEvent Struct:

    • Implements the Event interface and holds the kind and keycode of a custom event.
  4. Constants:

    • KeyDown and KeyUp define the constant values for key down and key up events.
  5. NewKeyEvent() Function:

    • Returns a new instance of the KeyEvent struct.
  6. StartEven() Method:

    • Enables the key event handling by setting the Enabled flag to true and starting the event channel.
    • Returns the event channel.
  7. StopEvent() Method:

    • Disables the key event handling by setting the Enabled flag to false and stopping the event channel.
    • 注意, 这个方法中, 会优先判断Enabled标志位,
  8. EventChannel() Method:

    • Returns the event channel.
  9. KindCode() and Keycode() Methods (for CustomEvent):

    • Implement the Event interface methods to return the kind and keycode of the custom event.
  10. CodeToChar() Method:

    • Converts a raw keycode to a character string using the hook.RawcodetoKeychar() function.

This code provides a way to handle keyboard events in a Go application, allowing you to listen for key down and key up events and retrieve the associated keycodes and characters. The CustomEvent struct allows you to define custom events with specific kind and keycode values.