views:

199

answers:

2

I need to include the asterisk as an allowable entry on a text box.

How can I test for this key under the KeyDown event regardless of the keyboard layout and language?

Ignoring the numeric keypad, with the Portuguese QWERTY layout this key can be tested through Keys.Shift | Keys.Oemplus. But that will not be the case for other layouts or languages.

+1  A: 

You are using the wrong event, you should be using KeyPressed. That fires when the user presses actual typing keys. KeyDown is useless here, the virtual key gets translated to a typing key according to the keyboard layout. Hard to guess what that might be unless you translate the keystroke yourself. That's hard.

Some code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
  string allowed = "0123456789*\b";
  if (allowed.IndexOf(e.KeyChar) < 0) e.Handled = true;
}

The \b is required to allow the user to backspace.

Hans Passant
I'm using the KeyPress event to handle this. Was wondering about the possibility of using KeyDown instead. But your answer reveals it's not possible. Thanks.
Krugar
+1  A: 

http://www.morethannothing.co.uk/2009/02/using-vkkeyscanex-to-find-out-what-keys-should-be-pressed-to-produce-a-character/ might help.

[Edit] It should be noted that regardless, handling KeyPressed is probably a better tactic.

ICR
Well, well. How about that. Very nice, ICR. Thanks.
Krugar