Applecore Pages on Microsoft Access

Trapping Keystrokes on a Form

There are two stages to trapping a keypress on a form. Firstly, you need to set the Form's KeyPreview property to Yes, so that the form gets the keystroke before the form, and then you will also need some code in the KeyDown event for the form:

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    Select Case KeyCode
        Case vbKeyEscape
            KeyCode=0
    End Select
End Sub

This will trap the Escape key being pressed, and result in no action being taken.

Another use is to create a continuous form that can be easily scrolled by using the cursor keys, to allow you to move up and down through the records by means of the up and down cursors, as well as through the fields for each record by using the left and right cursor keys. Again, set the Form's KeyPreview to Yes, and then use the Form's KeyDown event:

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    On Error GoTo E_Handle
    Select Case KeyCode
        Case vbKeyDown
            KeyCode = 0
            DoCmd.GoToRecord , , acNext
        Case vbKeyUp
            KeyCode = 0
            DoCmd.GoToRecord , , acPrevious
    End Select
sExit:
    Exit Sub
E_Handle:
    Select Case Err.Number
        Case 2105 'At start/beginning of records
        Case Else
            MsgBox Err.Description, vbOKOnly + vbCritical, "Error: " & Err.Number
    End Select
    Resume sExit
End Sub

If you want to trap keypresses on an application wide basis, then you might wish to look at the AutoKeys macro group.

Top

 


HOME | NEW | TABLES | QUERIES | FORMS | REPORTS | GENERAL | API | DOWNLOADS | TUTORIAL | RESOURCES
E-MAIL
Copyright & Disclaimer

 

Last modified at 06/06/2006 14:54:52