Option Explicit
[URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=If]#If[/URL] VBA7 Then
Private Declare PtrSafe Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
Private Declare PtrSafe Function SetTimer Lib "user32" (ByVal hwnd As LongPtr, ByVal nIDEvent As LongPtr, ByVal uElapse As Long, ByVal lpTimerFunc As LongPtr) As LongPtr
Private Declare PtrSafe Function KillTimer Lib "user32" (ByVal hwnd As LongPtr, ByVal nIDEvent As LongPtr) As Long
[URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=Else]#Else[/URL]
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
Private Declare Function SetTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Private Declare Function KillTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long) As Long
[URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=End]#End[/URL] If
Public Sub HookArrowKeys()
SetTimer Application.hwnd, 0, 0, AddressOf WatchKeyState
End Sub
Private Sub WatchKeyState()
Static bFirstRun As Boolean
Static bKeyReleased As Boolean
Static bArrowKeyWasPressed As Boolean
Static vKey As Variant
Dim bArrowKeyPressed As Boolean
Dim vKeysArray As Variant, vKeysNames As Variant, i As Integer
vKeysArray = Array(vbKeyDown, vbKeyUp, vbKeyLeft, vbKeyRight, vbKeyLButton, vbKeyReturn, vbKeyTab)
vKeysNames = Array("{DOWN}", "{UP}", "{LEFT}", "{RIGHT}", "{LEFT-CLICK}", "{ENTER}", "{TAB}")
For i = 0 To UBound(vKeysArray)
If GetAsyncKeyState(vKeysArray(i)) Then vKey = vKeysArray(i): bArrowKeyPressed = True: Exit For
Next i
On Error Resume Next
If bKeyReleased Or bFirstRun = False Then
bFirstRun = True
vKey = Switch(vKey = 38, "{UP}", vKey = 40, "{DOWN}", vKey = 39, "{RIGHT}", vKey = 37, _
"{LEFT}", vKey = 13, "{ENTER}", vKey = 9, "{TAB}", vKey = 1, "{LEFT-CLICK}")
KillTimer Application.hwnd, 0
Call ThisWorkbook.OnNavigationKeyDownPseudoEvent(Selection, vKey)
Call HookArrowKeys
End If
bKeyReleased = False
vKey = vKeysNames(i)
i = GetAsyncKeyState(vbKeyLButton)
If NavigationKeyStateUp Then
If bArrowKeyWasPressed Then
KillTimer Application.hwnd, 0
bKeyReleased = True
Call ThisWorkbook.OnNavigationKeyUpPseudoEvent(Selection, CStr(vKey))
End If
End If
bArrowKeyWasPressed = bArrowKeyPressed
If bArrowKeyPressed = False Then KillTimer Application.hwnd, 0
End Sub
Private Property Get NavigationKeyStateUp() As Boolean
NavigationKeyStateUp = GetAsyncKeyState(vbKeyDown) + GetAsyncKeyState(vbKeyUp) _
+ GetAsyncKeyState(vbKeyLeft) + GetAsyncKeyState(vbKeyRight) + GetAsyncKeyState(vbKeyReturn) + GetAsyncKeyState(vbKeyTab) = 0
End Property