Creating a Global Hotkey

Submitted by:Jhon Brain

Date added:10 November, 2012

Category:Visual Basic

Visual Basic code example for creating a Global Hotkey (active throughout Windows)

Tags: hotkey

Code Snippet:

' API Constants & Declarations
Public Const GWL_WNDPROC As Long = (-4)
Public Const WM_HOTKEY As Long = &H312

Public Const MOD_ALT = &H1
Public Const MOD_CONTROL = &H2
Public Const MOD_SHIFT = &H4

Public Declare Function GlobalAddAtom Lib "kernel32" Alias "GlobalAddAtomA" _
(ByVal lpString As String) As Long

Public Declare Function GlobalDeleteAtom Lib "kernel32" _
(ByVal nAtom As Long) As Long

Public Declare Function RegisterHotKey Lib "User32" _
(ByVal hWND As Long, _
ByVal id As Long, _
ByVal fsModifiers As Long, _
ByVal vk As Long) As Long

Public Declare Function UnregisterHotKey Lib "User32" _
(ByVal hWND As Long, _
ByVal id As Long) As Long

Public Declare Function SetWindowLong Lib "User32" Alias "SetWindowLongA" _
(ByVal hWND As Long, _
ByVal nIndex As Long, _
ByVal dwNewLong As Long) As Long

Public 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

Public mlngLastWndProc As Long
Public mlngAtom As Long

' Functions and Subroutines to store in main module
' Function which determines what happens when HotKey pressed
Function WindowProc(ByVal hWND As Long, ByVal uMsg As Long, _
ByVal wParam As Long, ByVal lParam As Long) As Long

If hWND = Clipboard_Mgr_Frm.hWND And uMsg = WM_HOTKEY Then
Clipboard_Mgr_Frm.Text1.Text = Clipboard_Mgr_Frm.Text1.Text & _
Clipboard.GetText(vbCFText) & vbCrLf & vbCrLf
End If

WindowProc = CallWindowProc(mlngLastWndProc, hWND, uMsg, wParam, lParam)
End Function

' Subroutine which creates the Hot Key
Public Sub CreateHotKey(ByVal intKeyCode As Integer, ByVal hWND As Long)
mlngAtom = GlobalAddAtom(CStr(Now))
mlngLastWndProc = SetWindowLong(hWND, GWL_WNDPROC, AddressOf WindowProc)
RegisterHotKey hWND, mlngAtom, 0, intKeyCode
End Sub

' Subroutine which destroys the hot key
Public Sub DestroyHotKey(ByVal hWND As Long)
UnregisterHotKey hWND, GlobalDeleteAtom(mlngAtom)
Call SetWindowLong(hWND, GWL_WNDPROC, mlngLastWndProc)
End Sub

' Procedures in a particular form
Private Sub Form_Load()
CreateHotKey vbKeyF2, Me.hWND
' Message below to let user know hot key has been created and what it does.
MsgBox "F2 is now a HOT KEY which will copy the clipboard contents" & vbCrLf & _
"To the textbox (minimized) - from ANYWHERE on the system!" & vbCrLf & vbCrLf & _
"REMEMBER to hit both Ctrl + C and F2 when copying text." & vbCrLf & vbCrLf & _
"MAXIMIZE from the Taskbar to Insert text in Word document.", vbOKOnly, _
" HOT KEY F2 PROCESS START"
End Sub

' Remember to destroy hot key when exiting the form
Private Sub cmdExit_Click()
DestroyHotKey Me.hWND
Unload Me
End
End Sub
 
 

Comments