Created
September 4, 2024 23:26
-
-
Save json-m/4cd4563f840aab0221fdde6ff400888c to your computer and use it in GitHub Desktop.
pure go way to send inputs to background windows using w32+syscall
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package input | |
import ( | |
"fmt" | |
"github.com/gonutz/w32/v2" | |
"syscall" | |
"time" | |
) | |
// some code for sending inputs to a window, regardless of whether it is in the foreground or not | |
var ( | |
user32 = syscall.NewLazyDLL("user32.dll") | |
procPostMessage = user32.NewProc("PostMessageW") | |
procMapVirtualKey = user32.NewProc("MapVirtualKeyW") | |
) | |
const ( | |
WM_KEYDOWN = 0x0100 | |
WM_KEYUP = 0x0101 | |
WM_CHAR = 0x0102 | |
MAPVK_VK_TO_VSC = 0 | |
) | |
type KeyHold struct { | |
VKCode uint16 | |
Duration time.Duration | |
} | |
// SendInputToWindow handles input type switching | |
func SendInputToWindow(hwnd w32.HWND, input interface{}) error { | |
switch v := input.(type) { | |
case string: | |
sendString(hwnd, v) | |
case KeyHold: | |
sendKeyHold(hwnd, v) | |
default: | |
return fmt.Errorf("unsupported input type") | |
} | |
return nil | |
} | |
// sendString types a string with small delay between characters into a window | |
func sendString(hwnd w32.HWND, text string) { | |
for _, char := range text { | |
_, _, _ = procPostMessage.Call( | |
uintptr(hwnd), | |
WM_CHAR, | |
uintptr(char), | |
0, | |
) | |
time.Sleep(time.Millisecond * 10) // small delay between characters | |
} | |
} | |
// sendKeyHold simulates a keypress event with key down duration | |
func sendKeyHold(hwnd w32.HWND, kh KeyHold) { | |
scanCode, _, _ := procMapVirtualKey.Call(uintptr(kh.VKCode), MAPVK_VK_TO_VSC) | |
lparam := (scanCode << 16) | 1 // repeat count is 1 | |
// key down | |
startTime := time.Now() | |
for time.Since(startTime) < kh.Duration { | |
_, _, _ = procPostMessage.Call( | |
uintptr(hwnd), | |
WM_KEYDOWN, | |
uintptr(kh.VKCode), | |
lparam, | |
) | |
time.Sleep(time.Millisecond * 10) | |
} | |
// key up at the end | |
_, _, _ = procPostMessage.Call( | |
uintptr(hwnd), | |
WM_KEYUP, | |
uintptr(kh.VKCode), | |
lparam|(1<<30)|(1<<31), // key up flag | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment