Key Press Event

  • Thread starter Thread starter Tim
  • Start date Start date
T

Tim

Hi Guys,

I want to know how to tell if the shift key is held down when another
key is pressed.

I am using the following code to make sure that only numbers, backspace
and decimal are allowed in a text box. I want to use the decimal on the
key, OemDecimal.

It can tell that the key is pressed but if the user holds the shift key
down then a > is inserted into the text box. How do I tell?

Thanks

Tim

// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if(e.KeyCode != Keys.Back && e.KeyCode != Keys.Decimal)
{
// A non-numerical keystroke was pressed.
// Set the flag to true.
nonNumberEntered = true;
}
}
}
 
Tim,

You might want to catch the KeyDown or the KeyUp event. These will pass
an KeyEventArgs instance to you which has a Shift property indicating if the
shift key was pressed (as well as ALT and CTRL).

Hope this helps.
 
Nicholas,

It only detects one key at a time. I need to detect if a key is pressed
while the shift key is held down. Any ideas?
 
Tim,

Nicholas was on the right track...the KeyEventArgs that is passed in each
time the KeyUp or KeyDown event is raised has a property called Shift that
returns a boolean value representing whether the shift key was pressed. It
also has properties for the Control and Alt keys as well.
 
Back
Top