-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunctions_windows.go
85 lines (68 loc) · 1.8 KB
/
functions_windows.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// +build windows
package main
import (
"fmt"
"syscall"
"time"
"github.com/Kethsar/w32"
"github.com/Kethsar/gform"
"github.com/atotto/clipboard"
)
var (
cbWin *gform.Form // This is to make sure we keep it in memory, I guess
)
/*
Attempt to listen for clipboard update events,
else just poll the clipboard sequence number (Like MS says not to whoops)
*/
func monitorClipboard() {
if createWindow() {
gform.RunMainLoop()
}
printToConsole("Error when creating window for monitoring clipboard")
printToConsole("Falling back to polling")
pollClipboard()
}
// Create a basic window and register it to receive clipboard update events
func createWindow() bool {
gform.Init()
cbWin = gform.NewForm(nil)
cbWin.Bind(w32.WM_CLIPBOARDUPDATE, cbUpdateHandler)
return w32.AddClipboardFormatListener(cbWin.Handle())
}
// Automatically called when Windows sends us a CLIPBOARDUPDATE event message
func cbUpdateHandler(arg *gform.EventArg) {
if data, ok := arg.Data().(*gform.RawMsg); ok {
if data.Msg == w32.WM_CLIPBOARDUPDATE &&
w32.IsClipboardFormatAvailable(w32.CF_UNICODETEXT) {
cb, err := clipboard.ReadAll()
if err != nil {
printToConsole(fmt.Sprintf("Error reading clipboard: %v", err))
} else {
syncClipoard(cb)
}
}
}
}
/*
Poll and cache the clipboard sequence number
This prevents constantly grabbing the clipboard itself
*/
func pollClipboard() {
u32 := syscall.NewLazyDLL("user32.dll")
getClipSequence := u32.NewProc("GetClipboardSequenceNumber")
var cbSeq uintptr
delay := time.NewTicker(500 * time.Millisecond)
for range delay.C {
r1, _, _ := getClipSequence.Call()
if r1 != cbSeq {
cbSeq = r1
cb, err := clipboard.ReadAll()
if err != nil {
printToConsole(fmt.Sprintf("Error reading clipboard: %v", err))
} else {
syncClipoard(cb)
}
}
}
}