GetKeyboardState Problem in C#

  • Thread starter Thread starter sharp
  • Start date Start date
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));
 
Hi sharp,
I tried your code and it works fine, but in different context.
It looks like that code snippet you posted is taken off of some windows
hook.
So I didn' try it with a windows hook. I just call the GetAsciiCharacter
method from form's keydown event

private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs
e)
{
Console.WriteLine("Key Pressed GetAscii: " +
GetAsciiCharacter((int)e.KeyCode, e.KeyValue));
}

In this context your method returns correct results.

What might be the problem? If you read in the MSDN about GetKeyboardState
you can find the following:

"An application can call this function to retrieve the current status of all
the virtual keys. The status changes as a thread removes keyboard messages
from its message queue. The status does not change as keyboard messages are
posted to the thread's message queue, nor does it change as keyboard
messages are posted to or retrieved from message queues of other threads.
(Exception: Threads that are connected through AttachThreadInput share the
same keyboard state.)"

So it might be possible that you have thread issues.
 
Back
Top