Click to See Complete Forum and Search --> : how to determine which keystroke?


pgugel
January 6th, 2003, 02:05 PM
I'd like to check which key on the keyboard was pressed. My first attempt looked somthing like this:

Private Sub Button1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Button1.KeyPress
If e = System.Windows.Forms.Keys.Left Then

End If
End Sub

This gets a syntax error on the right side of the equal sign. Anyone see what I'm doing wrong?

Thanks in advance.:)

Jym
January 6th, 2003, 04:38 PM
Are you trying to figure out if the button is left clicked or right clicked ? I just set up a blank form and put a button on it and the keypress didn't work for the mouse at all it worked only for the keyboard using your your code. Get rid of the if statement and put a break at the Private Sub ...

when you debug you will see it only breaks if there is a keypress not a button click

pgugel
January 7th, 2003, 08:14 AM
Actually, I'm trying to check if the left arrow was pressed. I'm trying to make the buttons (or any controls) movable. Depending on which control has focus, when an arrow key is pressed the control will be moved in that direction.

Jym
January 7th, 2003, 10:06 AM
I could be wrong, but wouldn't that be the sender and not e ?

pgugel
January 7th, 2003, 10:39 AM
I found that e.KeyChar references the key that was pressed. However, the arrow keys don't trigger the KeyPress event. Instead it changes the focus to the next control in the Tab Stop order.

Maybe I'll use the arrows on the number pad instead. These seem to trigger the KeyPress event - i.e., 4 = left, 2 = down, etc.

Thanks for the help Jym!

DdH
January 7th, 2003, 01:01 PM
To capture a key press on a empty form.

Set the KeyPreview property on the form = True

and implement the following code for your own form.

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
' Capture Keys
Select Case e.KeyCode
Case Keys.Left, Keys.NumPad4
' .......

Case Keys.Right, Keys.NumPad6
' .......

Case Keys.Up, Keys.NumPad8
' .......

Case Keys.Down, Keys.NumPad2
' .......

End Select
End Sub

This only works if you don't have any buttons on the form.
Because the the cursurkeys will switch the focus from button to button and the keydown event isn't raised.