I have a problem with changing keyboard layout inside keyboard hook. In this simple code, when pressing 'A' key, it takes a lot time, to change a language, in more complicated cases, application does wrong things..
Application works in tray, therefore I used hooks. Whats wrong with my code? )) Or, maybe there is different way to change keyboard layout, which works with hooks well? Thanks for your answers.
private static bool nextKey = false;
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
uint tpid = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
ushort currentLayout = GetKeyboardLayout(tpid);
if (nCode >= 0 && wParam == (IntPtr) WM_KEYDOWN) {
if (nextKey) {
Console.WriteLine("changing to english...");
PostMessage(GetForegroundWindow(), 0x0050, 0, (int) LoadKeyboardLayout("00000409", 0x00000001));
nextKey = false;
}
int vkCode = Marshal.ReadInt32(lParam);
if (vkCode == 0x41 && currentLayout == 0x409) { // if language is rus and 'A' pressed
Console.WriteLine("changing to russian...");
PostMessage(GetForegroundWindow(), 0x0050, 0, (int) LoadKeyboardLayout("00000419", 0x00000001));
nextKey = true;
}
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}