windows: add GetKeyboardLayout & ToUnicodeEx

These are used along with GetForegroundWindow and GetWindowThreadProcessId to determine the current user layout and translate the base key the user has pressed.

Change-Id: Ib833ba7ab54213d83e889ff74c5bc0ace5edbe95
GitHub-Last-Rev: 2afe9976a2d1f6a8dda9bd74cf07b207246bfcc6
GitHub-Pull-Request: golang/sys#188
Reviewed-on: https://go-review.googlesource.com/c/sys/+/574755
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Than McIntosh <thanm@google.com>
Reviewed-by: Alex Brainman <alex.brainman@gmail.com>
Reviewed-by: Ayman Bagabas <ayman.bagabas@gmail.com>
This commit is contained in:
Ayman Bagabas
2024-07-17 07:58:31 +00:00
committed by Alex Brainman
parent 0eac9b5475
commit bce4cf76d8
4 changed files with 101 additions and 2 deletions
+47
View File
@@ -1437,3 +1437,50 @@ uintptr_t beep(void) {
t.Fatal("LoadLibraryEx unexpectedly found beep.dll")
}
}
func TestGetKeyboardLayout(t *testing.T) {
fg := windows.GetForegroundWindow()
tid, err := windows.GetWindowThreadProcessId(fg, nil)
if err != nil {
t.Fatalf("GetWindowThreadProcessId failed: %v", err)
}
// We don't care about the result, just that it doesn't crash.
_ = windows.GetKeyboardLayout(tid)
}
func TestToUnicodeEx(t *testing.T) {
var utf16Buf [16]uint16
// Arabic (101) Keyboard Identifier
// See https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/windows-language-pack-default-values
ara, err := windows.UTF16PtrFromString("00000401")
if err != nil {
t.Fatalf("UTF16PtrFromString failed: %v", err)
}
araLayout, err := windows.LoadKeyboardLayout(ara, windows.KLF_ACTIVATE)
if err != nil {
t.Fatalf("LoadKeyboardLayout failed: %v", err)
}
var keyState [256]byte
ret := windows.ToUnicodeEx(
0x41, // 'A' vkCode
0x1e, // 'A' scanCode
&keyState[0],
&utf16Buf[0],
int32(len(utf16Buf)),
0x4, // don't change keyboard state
araLayout,
)
if ret != 1 {
t.Errorf("ToUnicodeEx failed, wanted 1, got %d", ret)
}
if utf16Buf[0] != 'ش' {
t.Errorf("ToUnicodeEx failed, wanted 'ش', got %q", utf16Buf[0])
}
if err := windows.UnloadKeyboardLayout(araLayout); err != nil {
t.Errorf("UnloadKeyboardLayout failed: %v", err)
}
}