0

I'm use this code for block the dollar button shift+4 = $. On this table http://expandinghead.net/keycode.html the $ is code 36

now the code on keydown:

if (e.KeyValue == 36)
{
    e.Handled = true;
}

code not work why?

david
  • 3,225
  • 9
  • 30
  • 43
Federal09
  • 639
  • 4
  • 9
  • 25
  • check this: http://stackoverflow.com/questions/8459067/winforms-capturing-the-combination-of-key-presses-using-processcmdkey-vs-keydo – MUG4N Oct 16 '13 at 12:00
  • 2000 line for one key?? No thanks! – Federal09 Oct 16 '13 at 12:02
  • This might not be an issue in your application, but be aware that if a user uses a different keyboard layout or if he copy-pastes a `$` from somewhere else he might bypass your validation. – dee-see Oct 16 '13 at 12:03
  • it's all about the keypreview property -_- – MUG4N Oct 16 '13 at 12:03
  • Never use KeyDown for typing keys, different keyboard layouts have different captions. Lots of cultures have layouts that don't have the $ at all, that's not the currency they use. Also the flaw in your code, you won't suppress NumberFormatInfo.CurrencySymbol for those users. The proper way to do this is to use the Validating event and format the entered value as a decimal without the currency symbol. – Hans Passant Oct 16 '13 at 12:26

2 Answers2

2

Why not on KeyPress event

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '$')
    {
        e.Handled = true;
    }
}
Colin Steel
  • 1,045
  • 1
  • 11
  • 24
  • 1
    Yep, that's what I'd use for specific chars (I'd use KeyDown for special keys such as PgDn or anything else which doesn't have a corresponding char) – Matthew Watson Oct 16 '13 at 12:04
0

This is because you first press shift and then 4, so you will get the code of shift (key value 16) separately when using KeyDown event.

To achieve what you want, use KeyPress event, not KeyDown. KeyPress will register the character you typed ($), not individual keys pressed.

if (e.KeyChar == '$')
{
    e.Handled = true;
}
Szymon
  • 42,577
  • 16
  • 96
  • 114