无法将virtualKey转换为unicode

时间:2018-07-09 13:16:00

标签: windows go user32

我正在尝试使用user32.dll中的ToUnicodeEx函数将virtualKey转换为unicode。根据文档,如果成功,此方法应返回1或更多。就我而言,它总是返回0。

procGetKeyboardState         = user32.NewProc("GetKeyboardState")
procMapVirtualKey            = user32.NewProc("MapVirtualKeyA")
procToUnicodeEx              = user32.NewProc("ToUnicodeEx")

...

func getKeyboardState(keyboardState *uint16) (len int32, err error) {
r0, _, e1 := syscall.Syscall(procGetKeyboardState.Addr(), 1, uintptr(unsafe.Pointer(keyboardState)), 0, 0)
len = int32(r0)

if len == 0 {
    if e1 != 0 {
        err = error(e1)
    } else {
        err = syscall.EINVAL
    }
}
return

}

...

func mapVirtualKey(uCode syscall.Handle) (scanCode syscall.Handle, err error) {
r0, _, e1 := syscall.Syscall(procMapVirtualKey.Addr(), 2, uintptr(uCode), 0, 0)

if e1 != 0 {
    err = error(e1)
    return
}
scanCode = syscall.Handle(r0)
return

}

...

func toUnicodeEx(virtKey syscall.Handle, scanCode syscall.Handle, keyState *uint16, pwszBuff *uint16) (value syscall.Handle) {
r0, _, _ := syscall.Syscall6(
    procToUnicodeEx.Addr(),
    6,
    uintptr(virtKey),
    uintptr(scanCode),
    uintptr(unsafe.Pointer(keyState)),
    uintptr(unsafe.Pointer(pwszBuff)),
    1,
    0,
)

value = syscall.Handle(r0)
return

}

...

keyboardBuf := make([]uint16, 200)
_, getKeyboardStateErr := getKeyboardState(&keyboardBuf[0])
if getKeyboardStateErr != nil {
    log.Fatalf("getKeyboardState -> %v", getKeyboardStateErr)
}

scanCode, mapVirtualKeyErr := mapVirtualKey(virtualCode)
if mapVirtualKeyErr != nil {
    log.Fatalf("mapVirtualKey -> %v", mapVirtualKeyErr)
}

unicodeBuf := make([]uint16, 200)
state := toUnicodeEx(virtualCode, scanCode, &keyboardBuf[0], &unicodeBuf[0])
fmt.Println("KEY BUFF ", keyboardBuf)
fmt.Println("SCAN CODE ", scanCode)
fmt.Println("UNICODE ", state, unicodeBuf)

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。您应该调用ToUnicode函数而不是ToUnicodeEx。

procToUnicode              = user32.NewProc("ToUnicode")

...

func toUnicode(virtKey syscall.Handle, scanCode syscall.Handle, keyState *uint16, pwszBuff *uint16) (value syscall.Handle) {
r0, _, _ := syscall.Syscall6(
    procToUnicode.Addr(),
    6,
    uintptr(virtKey),
    uintptr(scanCode),
    uintptr(unsafe.Pointer(keyState)),
    uintptr(unsafe.Pointer(pwszBuff)),
    1,
    0,
)

value = syscall.Handle(r0)
return
}

...

state := toUnicode(virtualCode, scanCode, &keyboardBuf[0], &unicodeBuf[0])