HandsOn Writing the Form KeyPress Event Procedure

1. In the Database window, right-click the Suppliers form and choose Copy.

2. Right-click in a blank area of the Database window and choose Paste.

3. Type Suppliers KeyPress as the name of the form and press OK.

4. Open the Suppliers KeyPress form in Design view.

5. Click the Properties button and, in the Form properties sheet, click the Event tab.

6. Set the Key Preview property to Yes.

Part IV

7. Set the On Key Press property to [Event Procedure] and press the Build button (...).

8. Access will create the event procedure stub. Enter the following Form_ KeyPress event procedure.

Private Sub Form_KeyPress(KeyAscii As Integer) Debug.Print "KeyAscii = " & KeyAscii & _

Space(1) & "= " & Chr(KeyAscii) If KeyAscii = 27 Then DoCmd.Close


KeyAscii = 0 End If End Sub

The statement KeyAscii = 0 will disable any input to all the controls on the form. Recall that a form's KeyPreview property determines whether form keyboard events are invoked before control keyboard events. To prevent keystrokes from going to the form's controls, the KeyPreview property must be set to Yes.

9. To test the above event procedure, open the Suppliers KeyPress form in Form view. Try to edit a field by typing some text. Because the input to all the controls on the form has been disabled by the Form_KeyPress event procedure, you cannot see any input. However, when you switch to the Immediate window, you will see the complete listing of keys that you pressed. Switch back to the Suppliers KeyPress form and press the Escape key to close this form.

0 -1

Post a comment