S
sharp
I have the code below to convert Virtual Keys using the Keyboard
state. The problem is that it seems that GetKeyboardState is not
working properly. The state comes back the same each time. For
example, I start the app with CAPS off and press the "f" key. ToAscii
returns the result of "f" properly. Then I press the CAPS ON and I
still get "f" from ToAscii. Some debugs reveal that he keyboard state
had not changed after the CAPS where put on.
If I restart the APP with CAPS ON I get "F" properly but then when I
turn CAPS off I still get "F".
It seems GetKeyboardState is returning the state the keyboard was in
when the app started.
Any Ideas?
[DllImport("user32.dll")]
public static extern bool ToAscii(int VirtualKey, int ScanCode,
byte[] lpKeyState, ref uint lpChar, int uFlags);
// Allows us to get current keyboard state.
[DllImport("user32.dll")]
public static extern int GetKeyboardState(byte [] lpKeyState);
protected char GetAsciiCharacter(int iKeyCode, int iFlags)
{
uint lpChar = 0;
byte[] bCharData = new byte[256];
GetKeyboardState(bCharData);
for(int i=0; i < 256; i++)
{
Console.WriteLine("[{0}] {1} {2}",i,
lastbCharData,bCharData);
}
ToAscii(iKeyCode, iFlags, bCharData, ref lpChar, 0);
for(int i=0; i < 256; i++)
{
lastbCharData =bCharData;
}
return (char)lpChar;
}
this is how the method is called:
Console.WriteLine("Key Pressed GetAscii: " +
GetAsciiCharacter(hookStruct.vkCode, hookStruct.scanCode));
state. The problem is that it seems that GetKeyboardState is not
working properly. The state comes back the same each time. For
example, I start the app with CAPS off and press the "f" key. ToAscii
returns the result of "f" properly. Then I press the CAPS ON and I
still get "f" from ToAscii. Some debugs reveal that he keyboard state
had not changed after the CAPS where put on.
If I restart the APP with CAPS ON I get "F" properly but then when I
turn CAPS off I still get "F".
It seems GetKeyboardState is returning the state the keyboard was in
when the app started.
Any Ideas?
[DllImport("user32.dll")]
public static extern bool ToAscii(int VirtualKey, int ScanCode,
byte[] lpKeyState, ref uint lpChar, int uFlags);
// Allows us to get current keyboard state.
[DllImport("user32.dll")]
public static extern int GetKeyboardState(byte [] lpKeyState);
protected char GetAsciiCharacter(int iKeyCode, int iFlags)
{
uint lpChar = 0;
byte[] bCharData = new byte[256];
GetKeyboardState(bCharData);
for(int i=0; i < 256; i++)
{
Console.WriteLine("[{0}] {1} {2}",i,
lastbCharData,bCharData);
}
ToAscii(iKeyCode, iFlags, bCharData, ref lpChar, 0);
for(int i=0; i < 256; i++)
{
lastbCharData =bCharData;
}
return (char)lpChar;
}
this is how the method is called:
Console.WriteLine("Key Pressed GetAscii: " +
GetAsciiCharacter(hookStruct.vkCode, hookStruct.scanCode));