当前位置:编程问答 > VB >

VB如何设置全局热键

问题:我想不管在哪里按键F5就弹出信息框
答案:''''''HOOK实现热键功能'''''''''
''传递Message给下一个HOOK
Public Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, ByVal nCode As Long, ByVal wParam As Long, lParam As Any) As Long
''安装HOOK
Public 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
''卸载HOOK
Public Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
''内存考贝
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
'键盘消息结构体类型
 
 ''键盘消息常数
 Public Const HC_ACTION = 0    ''键盘消息类型
 Public Const WH_KEYBOARD_LL = 13  ''消息类型
 Public lngHook As Long             ''消息句柄
 
 ''键盘消息常数 PostMessage
Public Const WM_KEYDOWN = &H100
Public Const WM_KEYUP = &H101
Public Const WM_CHAR = &H102
Public Const WM_SYSKEYDOWN = &H104
Public Const WM_SYSKEYUP = &H105
Public Const VK_A = &H41
Public Const VK_F1 = &H70
Public Const VK_CONTROL = &H11
Public Const VK_RETURN = &HD


 
 Public Type PKBDLLHOOKSTRUCT
            vkCode As Long
            scanCode As Long
            flags As Long
            time As Long
            dwExtraInfo As Long
 End Type

Public Function SetHotKey(ByVal nCode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Dim p As PKBDLLHOOKSTRUCT  '''定义一个键盘消息结构体变量
 
 If nCode = HC_ACTION Then  ''如果消息为键盘按下
    Select Case wParam      ''判断键盘参数
            Case WM_KEYDOWN, WM_SYSKEYDOWN
                 Call CopyMemory(p, ByVal lParam, Len(p))   '''拷贝内存的消息数据
                If p.vkCode = vbKeyF11 Then ''判断按键码
                       Form1.Print p.vkCode  '''这里做对消息的处理或检测消息做相关动作(不要用Msgbox弹对话框测试,系统会卡死)
                        
                End If
            Case Else
 
 End Select
 End If
 
 '''''''''''''''''''''原来的消息模式,键盘状态,键盘动作类型,0&''''''''''''''
 Call CallNextHookEx(WH_KEYBOARD_LL, nCode, wParam, lParam)   ''将消息传递给下个HOOK

 End Function

-----------------------------------------------------------

----以上的添加一个模块文件里面------------------

-----------------------------------------------------------

'调用代码

 

 

Private Sub Form_Load()
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''传0表示全局消息
lngHook = SetWindowsHookEx(WH_KEYBOARD_LL, AddressOf SetHotKey, App.hInstance, 0) '''安装键盘HOOK
End Sub

Private Sub Form_Unload(Cancel As Integer)
Call UnhookWindowsHookEx(lngHook)   '''''''卸载键盘HOOK

End Sub

Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer

'API

 

If GetAsyncKeyState(vbKeF5) Then '代码

MsgBox "你按下了F5键"

END IF

http://www.west263.com/info/html/chengxusheji/VB/20080224/23680.html

上一个:VB 怎么获取TXT的内容
下一个:请VB高手做些练习题

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,