Search code examples
ms-accessvbakeypress

How to Absorb a Keypress?


On my form I have an edit control. I have set up a KeyDown event to detect when the user pushes enter, but I also want to detect shift+space so the user can clear the contents of the box.

The functionality works - I can detect the keypress. Problem is that the space does not get absorbed and so the space glyph is still typed in the control.

How can I absorb the keypress when I push shift+space?

Private Sub FindBox_KeyDown(KeyCode As Integer, Shift As Integer)
    Select Case KeyCode
        Case vbKeyEnter: SearchForIt
        Case vbKeySpace:
            If Shift = 1 Then
                FindBox.Text = ""
                'here absorb keypress instead of sending space to control
                Exit Sub
            End If
    End Select
End Sub

Solution

  • You just need to set the value of KeyCode = 0. That will "swallow" the key and not have anything happen.

    You also want to use the bit mask to look for the presence of the shift being pressed

    Dim intShiftDown As Integer
    intShiftDown = (Shift And acShiftMask) > 0 
    
        Case vbKeySpace:
            If intShiftDown Then
                FindBox.Text = ""
                'here absorb keypress instead of sending space to control
                KeyCode = 0
                Exit Sub