# VBForums CodeBank > CodeBank - Visual Basic 6 and earlier >  VB6 - Using the KeyDown Event

## paralinx

I have seen a lot of people asking about using the Form_KeyDown event in the VisBasic 6 forum.  I know a lot of you know how to use this, but many do not, I am putting this in for future reference, so when someone asks a question about this, this thread can be sent.  So here is the code to run code when you press a key on the keyboard.


VB Code:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    'make sure KeyPreview is True on Form Properties
    On Error Resume Next
    Select Case KeyCode
        Case vbKey 'Then Find which key you want to use from the list below
            'Code to run when key is pressed
    End Select
End Sub

List of every key on the keyboard:


```
vbKeyLButton    Left Mouse Button
vbKeyRButton    Right Mouse Button
vnKeyCancel     Cancel Key
vbKeyMButton    Middle Mouse button
vbKeyBack       Back Space Key
vbKeyTab        Tab Key
vbKeyClear      Clear Key
vbKeyReturn     Enter Key
vbKeyShift      Shift Key
vbKeyControl    Ctrl Key
vbKeyMenu       Menu Key
vbKeyPause      Pause Key
vbKeyCapital    Caps Lock Key
vbKeyEscape     Escape Key
vbKeySpace      Spacebar Key
vbKeyPageUp     Page Up Key
vbKeyPageDown   Page Down Key
vbKeyEnd        End Key
vbKeyHome       Home Key
vbKeyLeft       Left Arrow Key
vbKeyUp         Up Arrow Key
vbKeyRight      Right Arrow Key
vbKeyDown       Down Arrow Key
vbKeySelect     Select Key
vbKeyPrint      Print Screen Key
vbKeyExecute    Execute Key
vbKeySnapshot   Snapshot Key
vbKeyInsert     Insert Key
vbKeyDelete     Delete Key
vbKeyHelp       Help Key
vbKeyNumlock    Delete Key

vbKeyA through vbKeyZ are the key code constants for the alphabet
vbKey0 through vbKey9 are the key code constants for numbers
vbKeyF1 through vbKeyF16 are the key code constants for the function keys
vbKeyNumpad0 through vbKeyNumpad9 are the key code constants for the numeric key pad

Math signs are:
vbKeyMultiply      -  Multiplication Sign (*)
vbKeyAdd             - Addition Sign (+)
vbKeySubtract     - Minus Sign (-)
vbKeyDecimal    - Decimal Point (.)
vbKeyDivide        - Division sign (/)
vbKeySeparator  - Enter (keypad) sign
```

----------


## |2eM!x

you need the keypreview property set to true also

----------


## paralinx

i have that if you look at the next line below the Private Sub Declaration  :Smilie:

----------


## st3ady

What if you want it to detect two simultaneous key presses? such as CTRL and F? Thanks!

----------


## paralinx

You could do something like

VB Code:
Dim CTRL_1 as Boolean
Dim CTRL_2 as Boolean
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    On Error Resume Next
    Select Case KeyCode
        Case vbKeyControl
            CTRL_1 = True
        Case vbKeyF
            CTRL_2 = True
    End Select
    If CTRL_1 And CTRL_2 Then Msgbox "Control F"
End Sub

----------


## |2eM!x

> You could do something like
> 
> VB Code:
> Dim CTRL_1 as Boolean
> Dim CTRL_2 as Boolean
> Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
>     On Error Resume Next
>     Select Case KeyCode
>         Case vbKeyControl
> ...


select case exits after it finds a true statement, so that wont work..

----------


## paralinx

Works for me.  Did you try it?

by the way I forgot one thing:

VB Code:
Dim CTRL_1 As Boolean
Dim CTRL_2 As Boolean
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    On Error Resume Next
    Select Case KeyCode
        Case vbKeyControl
            CTRL_1 = True
        Case vbKeyF
            CTRL_2 = True
    End Select
    If CTRL_1 And CTRL_2 Then
        MsgBox "Control F"
        CTRL_1 = False
        CTRL_2 = False
    End If
End Sub

----------


## Harsh Gupta

> Works for me.  Did you try it?
> 
> by the way I forgot one thing:
> 
> VB Code:
> Dim CTRL_1 As Boolean
> Dim CTRL_2 As Boolean
> Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
>     On Error Resume Next
> ...


paralinx,

this is not the perfect solution since CTRL+F means press F while keeping CTRL pressed. this will also work for:

1 - Pressing F after CTRL pressed n released
2 - Pressing CTRL after F pressed n released
3 - F + CTRL.

AFAIK, the only way to for this purpose is Sendkeys. though i may be wrong. there may exists some other methods.

----------


## |2eM!x

But this is not how select case works, it exits the whole thing after it finds something to match it.

[edit]
okay were not talking about the same thing here, I was thinking he meant pressing two keys at the exact same time..in this case harsh gupta's right on the money

----------


## Jacob Roman

This is what you need to be able to read more than one key pressed at the same time in pure VB:

http://www.vbforums.com/attachment.p...chmentid=36571

But if I were me, I'd typically be using DirectInput, as most of you already know  :Stick Out Tongue:

----------


## Stevanicus

Ok this is what i got that the mo and  it works alright

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    On Error Resume Next
    Select Case KeyCode
        Case vbKeyLeft
           imagedisplay.Left = imagedisplay.Left - 1
        Case vbKeyRight
            imagedisplay.Left = imagedisplay.Left + 1
        Case vbKeySpace
            value = value + 1
            If value = 2 Then
            Timer1.Enabled = True
            End If
    End Select
End Sub


just i what it so that when i press left and space, it doesnt stop left.... looked at the code from the attachment by jacob hehe no idea what was happening there :d can anyone help me i need something small but effective and simple

thanks

Steve

----------


## paralinx

Your not the only one, I looked at JR'd code and was quite confused myself.

I got your PM and I'll try to get your code to work  :Smilie:

----------


## paralinx

Ok here you go.  I coded this a bit oddly but the timer will not fire if you press Space and Arrow or just space or arrow  :Smilie: 


VB Code:
Option Explicit
    Dim KeyLeft As Boolean
    Dim KeySpace As Boolean
 Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    On Error Resume Next
        Select Case KeyCode
            Case vbKeyLeft
                If Not KeySpace Then KeyLeft = True
                imagedisplay.Left = imagedisplay.Left - 1
            Case vbKeyRight
                imagedisplay.Left = imagedisplay.Left + 1
            Case vbKeySpace
                If KeyLeft Then
                    KeySpace = True
                ElseIf Not KeyLeft Then
                    KeySpace = False
                End If
        End Select
        If KeySpace And KeyLeft Then
            Timer1.Enabled = True
            KeySpace = False
            KeyLeft = False
        End If
End Sub
 Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
    KeySpace = False
    KeyLeft = False
End Sub
 Private Sub Timer1_Timer()
    'Be sure to set your timer's interval to something
    imagedisplay.Left = imagedisplay.Left - 1
End Sub

----------


## Stevanicus

thanx

i'll try it out and let ya know

----------


## Stevanicus

thanx it works  :Big Grin:  !

thats great

----------


## paralinx

no problem my friend.

----------


## BigD_016

Hi,
I have a form with 3 groups of command buttons, each with 2 rows of buttons and each grouped into a separate picture box. I'm trying to get my prog. to be able to utilize the up and down arrow keys to make navigation easier. I have coded keyup and keydown events on the command button object. When I run the code the up and down buttons just go left and right through the command buttons on the form. I have set the keypreview property to true on my form. Any ideas? Please see code below:
_Private Sub Command1_KeyDown(index As Integer, KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyDown Then
Command1(index + 16).SetFocus
End If
End Sub

Private Sub Command1_KeyUp(index As Integer, KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyUp Then
Command1(index - 16).SetFocus
End If
End Sub_

----------


## paralinx

Hello Big_D, Welcome to the forums,

If I read correctly then you have 6 command buttons all together?

I could not use the arrow keys to move around the command buttons, so instead I used the up, down, left, and right keys on the numpad.  Also my code is kinda unorthadox like the rest of my code.

Here is your code  :Smilie: 



VB Code:
Private Sub Form_Load()
    'Changes the array of Command Buttons to have tags so I can recognize them
    Command1(0).Tag = "tl"
    Command1(1).Tag = "tm"
    Command1(2).Tag = "tr"
    Command1(3).Tag = "bl"
    Command1(4).Tag = "bm"
    Command1(5).Tag = "br"
End Sub
 Private Sub Command1_KeyDown(Index As Integer, KeyCode As Integer, Shift As Integer)
    Select Case KeyCode
        Case vbKeyNumpad6
            With Command1(Index)
                If .Tag = "tr" Then
                    Command1(0).SetFocus
                    Exit Sub
                ElseIf .Tag = "br" Then
                    Command1(3).SetFocus
                    Exit Sub
                End If
            End With
            Command1(Index + 1).SetFocus
        Case vbKeyNumpad4
            With Command1(Index)
                If .Tag = "tl" Then
                    Command1(2).SetFocus
                    Exit Sub
                ElseIf .Tag = "bl" Then
                    Command1(5).SetFocus
                    Exit Sub
                End If
            End With
            Command1(Index - 1).SetFocus
        Case vbKeyNumpad8
            With Command1(Index)
                If .Tag = "tl" Then
                    Command1(3).SetFocus
                    Exit Sub
                ElseIf .Tag = "tm" Then
                    Command1(4).SetFocus
                    Exit Sub
                ElseIf .Tag = "tr" Then
                    Command1(5).SetFocus
                    Exit Sub
                End If
            End With
            Command1(Index - 3).SetFocus
        Case vbKeyNumpad2
            With Command1(Index)
                If .Tag = "bl" Then
                    Command1(0).SetFocus
                    Exit Sub
                ElseIf .Tag = "bm" Then
                    Command1(1).SetFocus
                    Exit Sub
                ElseIf .Tag = "br" Then
                    Command1(2).SetFocus
                    Exit Sub
                End If
            End With
            Command1(Index + 3).SetFocus
    End Select
End Sub

If you have more than 6 command buttons I'll fix the code to work with how many you do, because I am not an english major and don't like reading  :Stick Out Tongue:

----------


## BigD_016

I actually have 32 buttons (16 on each line) in one group, 26 in another and 16 in yet another. I got your code to work fine with the number pad buttons, but it won't work for the arrow keys. Weird! Do you know if this is a bug with VB? DO you know any other way to get this to work with the arrow keys?   :Confused:

----------


## dglienna

Arrow keys are dependent upon the keyboard.  You could trap the keycodes of your keyboard, but they might not work on all other keyboards.  You should use the vbLeft keyword.

----------


## paralinx

So instead of Case vbKeyLeft use vbLeft... that will work?

----------


## BigD_016

Still no luck. The up and down arrow keys still just go left and right. I got the vbkeynumpad2 and vbkeynumpad8 to work just fine. If I turn numlock off though it gets treated like the arrow keys and only goes left and right. Any suggestions?????

----------


## marc_l4g

i need help how to control two scrollbars simultaneously when pressing both numpad: 4 and 8, or 6 and 2, or 4 and 2, or 6 and 8. please help me.

Private Sub Check1_KeyDown(KeyCode As Integer, Shift As Integer)
 On Error Resume Next
        Select Case KeyCode
      'first scrollbar
        Case vbKeyNumpad4
            If VScroll1.Value < 254 Then
                VScroll1.Value = VScroll1.Value + 1
            End If
        Case vbKeyNumpad6
            If VScroll1.Value > 1 Then
                VScroll1.Value = VScroll1.Value - 1
            End If

     'second scrollbar   
        Case vbKeyNumpad8
            If VScroll2.Value < 254 Then
                VScroll2.Value = VScroll2.Value + 1
            End If
        Case vbKeyNumpad2
            If VScroll2.Value > 1 Then
                VScroll2.Value = VScroll2.Value - 1
            End If
        End Select
End Sub

----------


## Al42

> What if you want it to detect two simultaneous key presses? such as CTRL and F? Thanks!



VB Code:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
  If (KeyCode = vbKeyF) And (Shift = vbCtrlMask) Then ...
End Sub
Shift = vbShiftMask
Ctrl = vbCtrlMask
Alt = vbAltMask

----------


## marc_l4g

Option Explicit
Dim X As Long
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer

Public Function CurLeft() As Boolean
    CurLeft = CBool(GetAsyncKeyState(37))
End Function
Public Function CurRight() As Boolean
    CurRight = CBool(GetAsyncKeyState(39))
End Function
Public Function CurUp() As Boolean
    CurUp = CBool(GetAsyncKeyState(38))
End Function
Public Function CurDown() As Boolean
    CurDown = CBool(GetAsyncKeyState(40))
End Function

Private Sub Form_Load()
    X = 0
End Sub

Private Sub Timer1_Timer()
    If (CurUp Or CurDown Or CurLeft Or CurRight) Then
        If CurUp = True Then
            Label1.Caption = "UP"
        End If
        If CurDown = True Then
            Label1.Caption = "DOWN"
        End If
        If CurDown = True and CurUp Then
            Label1.Caption = "DOWN and UP"
        End If

        If CurLeft = True Then
            Label1.Caption = "LEFT"
            X = X - 1
            Label2.Caption = X
        End If
        If CurRight = True Then
            Label1.Caption = "RIGHT"
            X = X + 1
            Label2.Caption = X
        End If
    Else: Label1.Caption = "NONE"
          X = 0
          Label2.Caption = X
    End If
End Sub

----------


## hinchies

Hey i am trying to use the keydown control to move an image across the form but when the form loads it has a command button selected and the image will not move. I have little experience with the set focus control and do not understand how to use it. Any help would be great.

----------


## rachelism

```
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown


        'Start the first stopWatch.
        sw1.Start()

       

    End Sub



    Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp



        'Turn off the first stopWatch.
        sw1.Stop()

        sec = sw1.ElapsedMilliseconds
           

   End Sub
```

this code actually work to count the time u pressing a key
when key down the stopwatch starts, when key up it stops.

Now, i try to start the stopwatch at 'key up' and stop at 'the next key down' (to count the time from key release till the next key being press)

i added a counter that looks like this:



```
dim counter_one as integer=0
dim counter_two as integer=0

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


        counter_two +=1

       if counter_two>=2 then

       sw1.stop()

        sec = sw1.ElapsedMilliseconds

        end if
        

    End Sub



    Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp

counter_one +=1

if counter_one>=1 then
sw1.start()
end if

        

   End Sub
```

but this doesn't work :Frown:  ..anyone knows why?

----------


## AC_AC_AC187

how do i check for CTRL & SHIFT being held in when clicking on a command button?



eg:



```
Private Sub cmdbtn_Click

If KeyDown = ctrl & shift Then
    'do some stuff
End If

'stuff to do

End Sub
```

----------


## richie11

I want to calculate the time interval between the keyup nd keydown event when i press a key can sommebody help me???????

----------


## Zero_Cool

I'm sorry if this question has been answered before, but with the keydown event I have developed a ping pong game and need to ping pong paddles to move simultaneously.

I have two paddles that are used by two players, players 1 uses "w" to move up and "s" to move down. Player 2 uses the up and down arrows. my code is as follows:



```
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

If KeyCode = vbKeyUp Then
        shpPaddle2.Move shpPaddle2.Left, shpPaddle2.Top - 8 'moves 8 pixels Up
        intPtop2 = shpPaddle2.Top
        intPbottom2 = (shpPaddle2.Top + shpPaddle2.Height)
    ElseIf KeyCode = vbKeyDown Then
        shpPaddle2.Move shpPaddle2.Left, shpPaddle2.Top + 8 'moves 8 pixels down
        intPtop2 = shpPaddle2.Top
        intPbottom2 = (shpPaddle2.Top + shpPaddle2.Height)
    End If
    
    If KeyCode = vbKeyW Then
        shpPaddle1.Move shpPaddle1.Left, shpPaddle1.Top - 8 'moves 8 pixels up
        intPtop = shpPaddle1.Top
        intPbottom = (shpPaddle1.Top + shpPaddle1.Height)
    ElseIf KeyCode = vbKeyS Then
        shpPaddle1.Move shpPaddle1.Left, shpPaddle1.Top + 8 'moves 8 pixels down
        intPtop = shpPaddle1.Top
        intPbottom = (shpPaddle1.Top + shpPaddle1.Height)
    End If
    
End Sub
```


is it possible to have this event and make two buttons pressed at once. Currently if two are pressed neither works, either one button can be pressed or both have to be held down at the exact same time.

----------


## Auledas

I make that following your explanation but it not rules... Can you see my error?


Option Explicit
Dim Marc As Boolean

Private Sub Command3_KeyDown(KeyCode As Integer, shift As Integer)
On Error Resume Next
Select Case KeyCode
Case vbKeyLButton
Marc = True
End select

If Marc = True Then
Label1.caption = "It rules"
End if

End sub


I need this to make a more complicated project and I will be really happy if you help me  :Big Grin:  Thanks.

----------


## LaVolpe

> I make that following your explanation but it not rules... Can you see my error?...


What is it that you are trying to do.
vbKeyLButton is same as vbLeftButton and is intended for use in Mouse events, not keyboard events.  See if this thread helps.

----------


## HighCommander

> What if you want it to detect two simultaneous key presses? such as CTRL and F? Thanks!


**** Straight from the VB6 Help file ****

Private Sub Text1_KeyDown (KeyCode As Integer, Shift As Integer)
   Dim ShiftDown, AltDown, CtrlDown, Txt
   ShiftDown = (Shift And vbShiftMask) > 0
   AltDown = (Shift And vbAltMask) > 0
   CtrlDown = (Shift And vbCtrlMask) > 0
   If KeyCode = vbKeyF2 Then   ' Display key combinations.
   If ShiftDown And CtrlDown And AltDown Then
      Txt = "SHIFT+CTRL+ALT+F2."
   ElseIf ShiftDown And AltDown Then
      Txt = "SHIFT+ALT+F2."
   ElseIf ShiftDown And CtrlDown Then
      Txt = "SHIFT+CTRL+F2."
   ElseIf CtrlDown And AltDown Then
      Txt = "CTRL+ALT+F2."
   ElseIf ShiftDown Then
      Txt = "SHIFT+F2."
   ElseIf CtrlDown Then
   Txt = "CTRL+F2."
   ElseIf AltDown Then
      Txt = "ALT+F2."
   ElseIf SHIFT = 0 Then
      Txt = "F2."
   End If
   Text1.Text = "You pressed " & Txt
   End If
End Sub

***********************************

The Shift argument lets you know if one of the three shift keys are being held down.  I think you are out of luck if you are trying to hold the T and X keys down at the same time.

To Expand on the VB6 sample:

Private Sub Text1_KeyDown (KeyCode As Integer, Shift As Integer)
   Dim ShiftDown as Integer
   Dim AltDown as Integer
   Dim CtrlDown as Integer

   ShiftDown = (Shift And vbShiftMask) > 0
   AltDown = (Shift And vbAltMask) > 0
   CtrlDown = (Shift And vbCtrlMask) > 0

   Select Case KeyCode
   Case vbKeyA
      Select Case Shift
      Case ShiftDown
         ' Option 1
      Case CtrlDown
         ' Option 2
      Case AltDown
         ' Option 3
      Case ShiftDown And CtrlDown
         ' Option 4
      Case ShiftDown And AltDown
         ' Option 5
      Case CtrlDown And AltDown
         ' Option 6
      Case CtrlDown And AltDown And CtrlDown
         ' Option 7
      Case Else
         ' Option 8 (No shift keys were pressed)
      End Select
   Case vbKeyB
      Select Case Shift
      Case ShiftDown
         ' Option 1
      Case CtrlDown
         ' Option 2
      Case AltDown
         ' Option 3
      Case ShiftDown And CtrlDown
         ' Option 4
      Case ShiftDown And AltDown
         ' Option 5
      Case CtrlDown And AltDown
         ' Option 6
      Case CtrlDown And AltDown And CtrlDown
         ' Option 7
      Case Else
         ' Option 8 (No shift keys were pressed)
      End Select
   Case vbKeyC
      Select Case Shift
      Case ShiftDown
         ' Option 1
      Case CtrlDown
         ' Option 2
      Case AltDown
         ' Option 3
      Case ShiftDown And CtrlDown
         ' Option 4
      Case ShiftDown And AltDown
         ' Option 5
      Case CtrlDown And AltDown
         ' Option 6
      Case CtrlDown And AltDown And CtrlDown
         ' Option 7
      Case Else
         ' Option 8 (No shift keys were pressed)
      End Select
   Case vbKeyD
      Select Case Shift
      Case ShiftDown
         ' Option 1
      Case CtrlDown
         ' Option 2
      Case AltDown
         ' Option 3
      Case ShiftDown And CtrlDown
         ' Option 4
      Case ShiftDown And AltDown
         ' Option 5
      Case CtrlDown And AltDown
         ' Option 6
      Case CtrlDown And AltDown And CtrlDown
         ' Option 7
      Case Else
         ' Option 8 (No shift keys were pressed)
      End Select
   Case vbKeyE
      Select Case Shift
      Case ShiftDown
         ' Option 1
      Case CtrlDown
         ' Option 2
      Case AltDown
         ' Option 3
      Case ShiftDown And CtrlDown
         ' Option 4
      Case ShiftDown And AltDown
         ' Option 5
      Case CtrlDown And AltDown
         ' Option 6
      Case CtrlDown And AltDown And CtrlDown
         ' Option 7
      Case Else
         ' Option 8 (No shift keys were pressed)
      End Select
   End Select
End Sub


And you can always remove the shift combos you don't need.

----------


## mig21

when i do this:

call Form_KeyDown(39,0)

it doesnt work why?

----------


## mig21

Hi,

when i use 

call Form_KeyDown(vbkeyleft,0)

it doesn't work why?

but if i use the keyboard it work's. :Confused:

----------


## HighCommander

Mig21,
If you start a new project and only place a button on the form,
then paste this code in the form, what happens when you run the program and click the button?



```
Private Sub Command1_Click()
  Call Form_KeyDown(vbKeyLeft, 0)
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
  Me.Caption = "KeyCode = " & CStr(KeyCode)
End Sub
```

I get the form caption changing to "KeyCode = 37"

----------

