Page 58 - Open Soource Technologies 304.indd
P. 58

Event Driven Programming



                           Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer)
                           If KeyCode = vbKeyBack Then
                           MsgBox “You pressed the backspace key!”
                           End If
                           End Sub

                          The Shift argument contains the value of the Shift, Control and Alt keys. This is useful for
                          performing a different action when one of these keys is pressed in combination with another  e.g.
                          pressing ‘A’ would be different to pressing ‘Ctrl+A’.

                                                 Constant       Value        Description
                                              vbShiftMask         1          Shift key
                                              vbCtrlMask          2          Ctrl key

                                              vbAltMask           4          Alt key

                          If a combination of these keys are pressed, the Shift argument will contain the sum of all keys
                          pressed  e.g. Ctrl+Alt would be 6.


                           Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer)
                           If Shift = vbCtrlMask + vbShiftMask Then
                           If KeyCode = vbKeyA Then
                           MsgBox “You pressed the Ctrl+Shift+A key combination!”
                           End If
                           End If
                           End Sub
                          KeyPress

                          KeyAscii As Integer
                          This event works differently to the KeyDown and KeyUp events in that it detects the actual
                          character (as the ANSI keycode) that is pressed rather than the keyboard key. For example:

                                                        Key  Pressed       Result
                                                        s               115
                                                        Shift           Nothing

                                                        Space           32

                          You can use the Chr function to convert the code into a letter  e.g., Chr(KeyAscii). If KeyAscii is
                          set to 0 in this event, this makes the program act as if the key was never pressed.

                          LostFocus
                          Occurs when the Command Button loses focus.



                          52                     LOVELY PROFESSIONAL UNIVERSITY
   53   54   55   56   57   58   59   60   61   62   63