I want to detect when the right shift key is released on a form in VB6. I have the following code:
Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
If GetKeyState(VK_RSHIFT) < 0 Then
MsgBox "Right Shift Released"
End If
End Sub
Except, it doesn’t work. By the time the event is fired the key has been released and the GetKeyState API function returns 0.
What’s the solution?
The Shift parameter tells you what combination of Shift, Ctrl, and Alt keys are down. It doesn’t distinguish between left and right, though. For that, you have to use the
GetKeyStateAPI function.Trap the right shift key when it goes down with similar code to what you have, but in the
Form_KeyDownevent. Set a module-level boolean to indicate that the key is now down. (Note that you’ll have to check thatKeyCodeis 16, which you’ll get for either shift key.)Then, in the
Form_KeyUpevent, if your boolean says the key is down, butGetKeyStatereturns a negative number indicating that it’s actually up, you know the key has been released. Make sure you reset the form-level boolean at this time as well.