When a user types into a VB.Net textbox, I want to detect the key press (assuming I cannot read the text from the textbox after its written). This is easy for English (by using e.KeyChar or Keys.[A, B, C, ...etc]). However, if I change my default keyboard in Windows from English to another language, say Arabic or Farsi, still the English characters are detected (although Arabic or Farsi is being typed in).
Join Stack Overflow to learn, share knowledge, and build your career.
You can do it by creating a table that maps the ASCII keycodes to the Persian character that you see on your keyboard.
VB:
'Create a look-up table
Dim Chars(256) As String
Chars(Asc('Q')) = 'ض';
Chars(Asc('W'))= 'ص';
Chars(Asc('E')) = 'ث';
' and so on...
'Now get it
Dim persianChar As String = Chars(e.KeyValue); 'You have your character
C#:
//Create a look-up table
char[] chars = new char[256];
chars['Q'] = 'ض';
chars['W'] = 'ص';
chars['E'] = 'ث';
// and so on...
//Now get it
char persianChar = chars[e.KeyValue]; //You have your character
-
I had thought of doing something like this, but the problem is that I will have to map every language I am working it. Isn't there a way to detect what was typed and in what language? – Muhammad Jan 22 '12 at 22:15
This kind of mishap could only be readily explained if you used the KeyDown instead of the KeyPress event. The KeyDown event reports virtual keys, their names are based on the layout of the original IBM PC keyboard, an English layout. The Keys type declares them in the .NET framework.
The KeyDown event is then further processed by Windows, using the selected keyboard layout. The underlying winapi function is ToUnicodeEx(). It has a lot of arguments, key ones are lpKeyState (keeps track of modifier keys and dead key state) and dwhkl (the selected keyboard layout). Changing the keyboard layout on your machine modifies that last argument. Which then trips the KeyPress event, its e.KeyCode argument is the utf-16 Unicode codepoint if the keystroke represents a typing key.
Never attempt to interpret the KeyDown event yourself. You should override ProcessCmdKey() to detect shortcut key strokes like Ctrl+F1. Always use the KeyPress event for typing keys.
-
Thanks for the explanation Hands, but I am afraid most of it went over my head; I am afraid you will need to bring it down to my level of understanding. What I understood is that using ToUnicodEx one can detect the keyboard language and thus be able to map the press key to a character in the keyboard language? Could you please write a few lines? – Muhammad Jan 22 '12 at 22:18
-
Key Codes are simply the signals received from the keyboard - the OS interprets these into whatever the current input language is.
If you want to test whether the last character entered belongs to a specific language, you will need to test the character directly from the textbox (check that the value falls within the right Unicode range).