keycodes

juggernot

Well-known member
Joined
Sep 28, 2006
Messages
173
Programming Experience
Beginner
I'm trying to make a program where, depending on what keys you press, a button will move a certain direction. I'd like some help using keycodes. I'm just playing around with them, never used them before. So far I can't get them to work.Right now my code looks like this:

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown

If e.KeyCode = Keys.A Then
Varleft = true
ElseIf e.KeyCode = Keys.B Then
Varright = true
End If

Than, in a timer I have the following code:

If Varleft = True Then
Me.Button1.left += -2
ElseIf Varright = True Then
Me.Button1.left += 2
 
I'm not sure what your question is here? Are you using the code above and the move is not happening? Are you getting an error, or just no action at all?
 
Does the form have focus?

If so, you could try using the keypress event.

VB.NET:
 Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
        If e.KeyChar = "a" Then MySub()
    End Sub
I think that should work? Then in the sub, do you stuff...
You could maybe create a variable, which could equal 1 for left and 2 for right?
Then call the sub at the end of keypress, if no matches, set it to 0 or dont call the sub etc
In the sub, check the var and do the required action accordingly?

I used a integer, as im not sure if you are planning on adding more keys.

Hope that helps :)
 
nothing happens at all with my code, raven. I'm going to check to see if what Leon said can help me out.
 
juggernet, you are handling keydown event for the form, this requires the form to have focus, and not any control on that form. There exist a form property KeyPreview that may help you, it got this description:
Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.
 
Back
Top