Key Press Event



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?



// 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;

Nicholas Paldino [.NET/C# MVP]


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.



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?



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.

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question