Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Like
1Likes
Dislike

Converting Scan Codes to ASCII

By Photon | Published Nov 12 1999 04:06 AM in DirectX and XNA

key scan various codes layout ascii return static using
If you find this article contains errors or problems rendering it unreadable (missing images or files, mangled code, improper text formatting, etc) please contact the editor so corrections can be made. Thank you for helping us improve this resource

It is often the case in games, that keyboard input is needed to input text, rather than be used for usual game controls. This poses three basic problems:
  • Key identifiers in DirectInput are keyboard scan codes.
  • Various international keyboards map scan codes differently, according to their layout.
  • The same scan code can be translated to various ASCII codes, depending on the status of the shift key, and other such cases.
To solve this problem, we can use various Win32 API calls to resolve which ASCII code the key should be translated to.

These are the steps we'll use:
  • We'll use GetKeyboardLayout() to get the current keyboard layout.
  • GetKeyboardState() will be used to retrieve the state of keys like shift, ctrl, alt, etc.
  • Then using the current layout and scan code, using MapVirtualKeyEx() will give us a win32 virtual key (UINT type).
  • The ToAsciiEx() function will finally convert the virtual key to 0 - 2 extended ASCII characters (unsigned short)
Here's a sample function:

static int scan2ascii(DWORD scancode, ushort* result)
{
   static HKL layout=GetKeyboardLayout(0);
   static uchar State[256];

   if (GetKeyboardState(State)==FALSE)
  	return 0;
   UINT vk=MapVirtualKeyEx(scancode,1,layout);
   return ToAsciiEx(vk,scancode,State,result,0,layout);
}

This returns the number of characters extracted. It will return 0 in the case that there was no conversion, or 1 or 2, depending multibyte character sets, for a valid output.

In most cases, using char(result[0]) would provide the desired output.





Comments
I've tried this and a very other variations but MapVirtualKeyEx will only return 0 for me. Any help would be amazing.

Note: Please offer only positive, constructive comments - we are looking to promote a positive atmosphere where collaboration is valued above all else.




PARTNERS