Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Capture Shift Key if Pressed on A form

virusworld

Programmer
Nov 28, 2024
1
suppose you have a btn1 on form
and you want to use this button in multiple ways so if shift key is pressed and you click on that button it will open form2 else open form1
to do That :
1- Enable Key Preview in Form
2- declare An integer to the form ( dim ShiftPressed as Integer)
3 - Add Form_KeyDown event:

Code:
[CODE]Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyShift Then
ShiftPressed= 1 End If
End Sub
[/CODE]

4 - Add Form_KeyUp event :

Code:
[CODE]Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyShift Then
ShiftPressed= 0 End If
End Sub
[/CODE]

5 - Btn1 Click Event:

Code:
btn1_Click()
if ShiftPressed = 0 then
docmd.openForm "form1"
else
docmd.openForm "form2"
end if
 
I'm not seeing a question here, but I'm guessing using the form events is not working for you. That's because you need to "select" the form to detect the "Key" events. And that is hard to do and even harder to manage.

Instead, I think you want to use the KeyUp and KeyDown events on the button. But this gets tricky because the KeyUp and KeyDown events are detected anywhere on the form, not just when the mouse is over the button.

Here's what that might look like for a form:

Code:
Option Compare Database
Option Explicit

Private shiftKeyPressed As Boolean

Private Sub cmdButton_Click()
    If shiftKeyPressed Then
        Me.lblWithShift.Visible = True
        Me.lblNoShift.Visible = False
    Else
        Me.lblWithShift.Visible = False
        Me.lblNoShift.Visible = True
    End If
End Sub

Private Sub cmdButton_KeyDown(KeyCode As Integer, Shift As Integer)
    If (Shift And acShiftMask) <> 0 Then
        shiftKeyPressed = True
        Me.lblShiftKeyState.Visible = True
    End If
End Sub

Private Sub cmdButton_KeyUp(KeyCode As Integer, Shift As Integer)
    If (Shift And acShiftMask) <> 0 Then
        shiftKeyPressed = False
        Me.lblShiftKeyState.Visible = False
    End If
End Sub

Private Sub Form_Open(Cancel As Integer)
    shiftKeyPressed = False
    Me.lblShiftKeyState.Visible = False
    Me.lblNoShift.Visible = False
    Me.lblWithShift.Visible = False
End Sub
 
Rich (BB code):
Private Const VK_SHIFT As Long = &H10
Private Declare Function GetAsyncKeyState Lib "user32.dll" (ByVal vKey As Long) As Integer
Private Const KeyDown As Integer = &H8000

Private Sub Command0_Click()
    If CBool(GetAsyncKeyState(VK_SHIFT) And KeyDown) Then
        DoCmd.OpenForm "form2"
    Else
        DoCmd.OpenForm "form1"
    End If 
End Sub
 

Part and Inventory Search

Sponsor

Back
Top