一般有两种方法, RegisterHotKey 和 Hook
RegisterHotKey 的方法相对比较简单,就是向Windows注册这个热键,然后就能用了
========================以下程序未经测试===============================
新建立一个FORM~
Private Sub Form_Load()
Dim ret As Long
preWinProc = GetWindowLong(Me.hwnd, GWL_WNDPROC)
ret = SetWindowLong(Me.hwnd, GWL_WNDPROC, AddressOf Wndproc)
idHotKey = 1
Modifiers = MOD_ALT + MOD_CONTROL
uVirtKey = vbKeyA
ret = RegisterHotKey(Me.hwnd, idHotKey, Modifiers, uVirtKey)
End Sub
Private Sub Form_Unload(Cancel As Integer)
Dim ret As Long
ret = SetWindowLong(Me.hwnd, GWL_WNDPROC, preWinProc)
Call UnregisterHotKey(Me.hwnd, uVirtKey)
End Sub
新建立一个模块
Option Explicit
Declare Function SetWindowLong Lib "User32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Declare Function GetWindowLong Lib "User32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Declare Function CallWindowProc Lib "User32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Declare Function RegisterHotKey Lib "User32" (ByVal hwnd As Long, ByVal id As Long, ByVal fsModifiers As Long, ByVal vk As Long) As Long
Declare Function UnregisterHotKey Lib "User32" (ByVal hwnd As Long, ByVal id As Long) As Long
Public Const WM_HOTKEY = &H312
Public Const MOD_ALT = &H1
Public Const MOD_CONTROL = &H2
Public Const MOD_SHIFT = &H4
Public Const GWL_WNDPROC = (-4)
Public preWinProc As Long
Public Modifiers As Long, uVirtKey As Long, idHotKey As Long
Private Type taLong
ll As Long
End Type
Private Type t2Int
lWord As Integer
hWord As Integer
End Type
Public Function Wndproc(ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
If Msg = WM_HOTKEY Then
If wParam = idHotKey Then
Dim lp As taLong, i2 As t2Int
lp.ll = lParam
LSet i2 = lp
If (i2.lWord = Modifiers) And i2.hWord = uVirtKey Then
msgbox "你按下了热键哦~"
End If
End If
End If
Wndproc = CallWindowProc(preWinProc, hwnd, Msg, wParam, lParam)
End Function
========================以上程序未经测试===============================
另外有人已经写成了模块,见用 VB 实现全局热键模块
还有另外一篇:VB中定义全局热键
第二种方法是Hook(俗称"钩子"),这个比较复杂一些,一些木马啊什么的,也是用这个实现的.
介绍Hook的文章很多,随便找了一些,没时间看