16 May 2010

Virtual-key code to ANSI character

The Ocx_KeyDown event and the function Gfa_KeyGet (GFA-BASIC editor extension) provide a virtual-key code representing the key pressed. However, it doesn't take the shift-state into account. (The Screen_PreView event sub passes WM_KEYDOWN messages as well.)
In all cases you want to process a WM_KEYDOWN message the ANSI character isn't known. To convert a virtual-key code plus a shift state to an ANSI character you need ToAscii() API. This function takes the virtual-key code and the keyboard state and translates it to an ANSI character. I use it as follows:

' Press shift-key than click mouse
Do :   Sleep : Until MouseK
Trace Chr(VkKeyToAscii(65))
Trace Chr(VkKeyToAscii(Asc("8"))) ' –> *

Function VkKeyToAscii(keycode As Int) As Int
  Dim sb As String * 4

  Static Dim keyboardState(256) As Byte
  ~GetKeyboardState(ArrayAddr(keyboardState()))

  If ToAscii(keycode, 0, ArrayAddr(keyboardState()), sb, 0) == 1
    Return Asc(sb)
  Else
    Return 0
  EndIf

EndFunc

No comments:

Post a Comment