KeyPress - 64-bit
Để chạy ví dụ trên Excel 64-bit cần sửa code như sau.
[GPECODE=vb]
Option Explicit
#If VBA7 Then
Declare PtrSafe Function SetWindowsHookEx Lib _
"user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As LongPtr, _
ByVal hmod As LongPtr, ByVal dwThreadId As LongPtr) As LongPtr
Declare PtrSafe Function CallNextHookEx Lib "user32" _
(ByVal hHook As LongPtr, ByVal nCode As Long, ByVal wParam As LongPtr, lParam As Any) As LongPtr
Declare PtrSafe Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As LongPtr) As LongPtr
Declare PtrSafe Function GetActiveWindow Lib "user32" () As LongPtr
Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Dim hhkLowLevelKybd As LongPtr
#Else
Declare Function SetWindowsHookEx Lib _
"user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As Long, _
ByVal hmod As Long, ByVal dwThreadId As Long) As Long
Declare Function CallNextHookEx Lib "user32" _
(ByVal hHook As Long, ByVal nCode As Long, ByVal wParam As Long, lParam As Any) As Long
Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
Declare Function GetActiveWindow Lib "user32" () As Long
Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Dim hhkLowLevelKybd As Long
#End If
Const HC_ACTION = 0
Const WM_KEYDOWN = &H100
Const WH_KEYBOARD_LL = 13
Type KBDLLHOOKSTRUCT
vkCode As Long
scanCode As Long
flags As Long
time As Long
dwExtraInfo As Long
End Type
#If VBA7 Then
Function Cell_OnKeyDown(ByVal nCode As Long, ByVal wParam As LongPtr, lParam As KBDLLHOOKSTRUCT) As LongPtr
#Else
Function Cell_OnKeyDown(ByVal nCode As Long, ByVal wParam As Long, lParam As KBDLLHOOKSTRUCT) As Long
#End If
Dim keyCode As Long
keyCode = lParam.vkCode
If GetActiveWindow = FindWindow("XLMAIN", Application.Caption) Then
If (nCode = HC_ACTION) Then
If wParam = WM_KEYDOWN Then
' Xu ly su kien tai day
Select Case keyCode
Case vbKey0 To vbKey9, vbKeyUp, vbKeyDown, vbKeyLeft, vbKeyRight, vbKeyF2, _
vbKeyReturn, vbKeyEscape, vbKeyBack, vbKeyDelete, vbKeyHome, vbKeyEnd, _
vbKeyTab
Cell_OnKeyDown = 0
Case Else
Cell_OnKeyDown = -1
Exit Function
End Select
End If
End If
End If
Cell_OnKeyDown = CallNextHookEx(0, nCode, wParam, ByVal lParam)
End Function
Sub ActiveEvent(rng As Range)
Unhook_KeyBoard
hhkLowLevelKybd = SetWindowsHookEx(WH_KEYBOARD_LL, AddressOf Cell_OnKeyDown, Application.Hinstance, 0)
SaveHookIDToReg hhkLowLevelKybd
End Sub
Public Sub Unhook_KeyBoard()
If hhkLowLevelKybd = 0 Then
hhkLowLevelKybd = GetHookIDfromReg()
End If
If hhkLowLevelKybd <> 0 Then UnhookWindowsHookEx hhkLowLevelKybd
End Sub
Sub SaveHookIDToReg(ByVal nHookID As LongPtr)
SaveSetting "MyXlApp", "KEYBOARD", "HookID", nHookID
End Sub
Function GetHookIDfromReg() As LongPtr
GetHookIDfromReg = CLng(GetSetting("MyXlApp", "KEYBOARD", "HookID", 0))
End Function
[/GPECODE]