Option Explicit
Private Type POINTAPI
x As Long
y As Long
End Type
Private Type MSG
hwnd As Long
Message As Long
wParam As Long
lParam As Long
time As Long
pt As POINTAPI
End Type
Private Declare Function WaitMessage Lib "user32" () As Long
Private Declare Function TranslateMessage Lib "user32" _
(ByRef lpMsg As MSG) As Long
Private Declare Function PeekMessage Lib "user32" _
Alias "PeekMessageA" _
(ByRef lpMsg As MSG, ByVal hwnd As Long, _
ByVal wMsgFilterMin As Long, _
ByVal wMsgFilterMax As Long, _
ByVal wRemoveMsg As Long) As Long
Private Declare Sub mouse_event Lib "user32" _
(ByVal dwFlags As Long, _
ByVal dx As Long, _
ByVal dy As Long, _
ByVal cButtons As Long, _
ByVal dwExtraInfo As Long)
Private Const WM_SYSKEYDOWN As Long = &H104
Private Const WM_KEYDOWN = &H100
Private Const WM_CHAR As Long = &H102
Private Const PM_REMOVE As Long = &H1
Private Const MOUSEEVENTF_LEFTDOWN = &H2
Private Const MOUSEEVENTF_LEFTUP = &H4
Private bCancelLoop As Boolean
Private bHookSet As Boolean
Sub StartHook()
If Not bHookSet Then
bHookSet = True
Call HookKeyBoard
End If
End Sub
Sub TerminateHook()
'reset flags.
bCancelLoop = True
bHookSet = False
End Sub
Private Sub HookKeyBoard()
Dim msgMessage As MSG
'initialize the flag.
bCancelLoop = False
Application.OnDoubleClick = "CANCEL_DBLCLCK"
Application.EnableCancelKey = xlDisabled
'start loop to monitior key presses.
Do While Not bCancelLoop
'wait for an input message.
WaitMessage
'check for a key press.
If PeekMessage _
(msgMessage, 0, WM_KEYDOWN, WM_KEYDOWN, PM_REMOVE) Or _
PeekMessage(msgMessage, 0, WM_SYSKEYDOWN, _
WM_SYSKEYDOWN, PM_REMOVE) _
Then
'for all other keys retrieve their ascii codes and
TranslateMessage msgMessage
PeekMessage msgMessage, 0, WM_CHAR, _
WM_CHAR, PM_REMOVE
'send the KeyCodes to the worksheet.
ActiveCell = "'" & CStr(ActiveCell) & "-" & CStr(msgMessage.wParam)
End If
'allow processing other msgs.
DoEvents
Loop
Application.EnableCancelKey = xlInterrupt
Application.OnDoubleClick = ""
MsgBox "Done.", vbInformation
End Sub
Private Sub CANCEL_DBLCLCK()
mouse_event MOUSEEVENTF_LEFTDOWN Or MOUSEEVENTF_LEFTUP, _
0&, 0&, 0&, 0&
DoEvents
End Sub