6

I have a small WIN32 C-Application in which i work with the KBDLLHOOKSTRUCT structure. This structure contains the VK-Code for a pressed key.

I try to convert this to an ASCII-Character. For this i use the Function MapVirtualKey, which works well.

The only problem is, that one VK-Code can stay for multiple chars. Example:

On my keyboard (Swiss-German) exists the key-char .. If i press Shift+. then it creates a :. The VK-Code is the same. Thats no problem, and i can also check if Shift is pressed or Caps Lock is activated.

My only problem is: How can i get the char ':'? I need a function like this:

GetKeyChar(vkCode, shift)

I need this to get the "normal" and the "shifted" value of the keyboard. Of course i could hardcode this, but i don't like to do it on this way.

phihag
  • 278,196
  • 72
  • 453
  • 469
Kevin Meier
  • 2,339
  • 3
  • 25
  • 52
  • Wrong function, ToUnicodeEx() required. You'll have much bigger problems with dead keys, present on German keyboards. Proper translation requires the keyboard state, it is a per-process property. You can only easily get the keyboard state of your own process, not of the process that currently has the focus. I've never seen a solution for this. – Hans Passant Sep 04 '11 at 14:29
  • actually the keyboard state is per-thread – Bevan Collins Sep 06 '11 at 20:13

4 Answers4

4

The problem is that the KBDLLHOOKSTRUCT doesn't have all the information you need in order to do the translation. You get a message every time a key is pressed. So for Shift+X, you'll get an input message saying that the Shift key was pressed, and another message saying that the "X" key was pressed.

You need to call GetKeyboardState in order to get the state of the Shift, Alt, Ctrl, (and perhaps other) keys. Then call ToAsciiEx or ToUnicodeEx.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • For a keyboard hook wouldn't it be more appropriate to update a keystate array manually from the input events? (something like `BYTE k = kb.vkCode; keystate[k]&=0x80; if(!(kb.flags&LLKHF_UP)) keystate[k]|=0x80;`) – user786653 Sep 04 '11 at 14:42
  • Ok, thanks. This worked, i combined GetKeyboardState with ToAsciiEx. The dead keys are not good, but it's not a big problem. – Kevin Meier Sep 04 '11 at 15:41
  • @user786653: yes, you're correct. In a hook you'd probably want to maintain your own keyboard state structure from the events rather than by calling the API. – Jim Mischel Sep 04 '11 at 21:03
2

You're looking for ToUnicode, which returns the unicode character generated by that keypress.

phihag
  • 278,196
  • 72
  • 453
  • 469
2

The functions you are looking for are: ToAscii, ToAsciiEx, ToUnicode, ToUnicodeEx.

Alex F
  • 42,307
  • 41
  • 144
  • 212
0

short VkKeyScan(char ch) API has contained the shift information. It translate char to virtual-key code and shift state.

See this: Convert character to the corresponding virtual-key code

Community
  • 1
  • 1
Green Su
  • 2,318
  • 2
  • 22
  • 16