//go:build windows package scanbridge // 用 Windows user32.SendInput 以 Unicode 方式模拟键盘输入(HID 模式), // 把文本注入到「当前前台窗口 + 当前光标」位置,不受键盘布局影响。 // // 关键优化: // 1. 逐字符节流(kbdDelay,默认 2ms):模仿真实 HID 扫码枪的固定输出速率。 // 原本把整串按键「瞬时一次性」灌进去,会灌爆前台程序的消息队列, // 导致「一个字一个字往外蹦 / 卡顿 / 甚至掉字」——节流正是为此。 // 2. 完整 UTF-16 处理:先转 UTF-16 code unit,非 BMP 字符(>0xFFFF,如 emoji) // 会正确拆成代理对,不再被 uint16(r) 截断。 // 3. 最后一个字符后不再多余 sleep;kbdDelay=0 时回退为整串一次发出。 import ( "syscall" "time" "unicode/utf16" "unsafe" ) var procSendInput = syscall.NewLazyDLL("user32.dll").NewProc("SendInput") const ( inputKeyboard = 1 keyeventfUnicode = 0x0004 keyeventfKeyup = 0x0002 ) // input 精确对齐 Windows INPUT 结构(64 位下 40 字节:DWORD type + 4 填充 + KEYBDINPUT(24) + 8 填充到 union 尺寸)。 type input struct { typ uint32 _pad0 uint32 wVk uint16 wScan uint16 dwFlags uint32 time uint32 dwExtraInfo uintptr _pad1 [8]byte } // sendStringAsKeyboard 模拟键盘逐字符输入字符串(纯文本,不追加回车)。 // // 字符之间按包级 kbdDelay 节流: // - kbdDelay > 0 :每个 UTF-16 码元单独投递一对 按下/抬起 事件,之间 sleep kbdDelay, // 观感"快速顺滑地滑出",且不会掉字; // - kbdDelay <= 0:整串事件一次 SendInput 发出(最快,但部分程序可能卡顿/掉字)。 func sendStringAsKeyboard(s string) error { if s == "" { return nil } // Windows 的 KEYEVENTF_UNICODE 是按 UTF-16 code unit 投递的, // 先做 UTF-8 → UTF-16 转换,非 BMP 字符会在此正确拆成一对代理码元。 units := utf16.Encode([]rune(s)) if kbdDelay <= 0 { inputs := make([]input, 0, len(units)*2) for _, u := range units { inputs = append(inputs, input{typ: inputKeyboard, wScan: u, dwFlags: keyeventfUnicode}) inputs = append(inputs, input{typ: inputKeyboard, wScan: u, dwFlags: keyeventfUnicode | keyeventfKeyup}) } return sendInputs(inputs) } for i, u := range units { pair := [2]input{ {typ: inputKeyboard, wScan: u, dwFlags: keyeventfUnicode}, {typ: inputKeyboard, wScan: u, dwFlags: keyeventfUnicode | keyeventfKeyup}, } if err := sendInputs(pair[:]); err != nil { return err } if i < len(units)-1 { time.Sleep(kbdDelay) } } return nil } // sendInputs 调用 SendInput 投递一批键盘事件,并校验返回的事件数。 func sendInputs(inputs []input) error { if len(inputs) == 0 { return nil } ret, _, err := procSendInput.Call( uintptr(len(inputs)), uintptr(unsafe.Pointer(&inputs[0])), uintptr(unsafe.Sizeof(inputs[0])), ) if int(ret) != len(inputs) { if err == nil { err = syscall.EINVAL } return err } return nil }