Q&A (Continued)
Q: Add Hotkey Support
I want to create a program that usually runs in the background, but pops up and becomes the active task if the user presses (for example) Ctrl-1 at any time. Someone pointed me to the RegisterHotKey API. Can you tell me more about it? Is a subclass required in this case?
A:
You're on the right track. RegisterHotKey is the correct API—this call instructs the system to send you a notification if the user presses the indicated key or key combination. Classic VB doesn't give you access to the main thread's message queue, so the easiest way of sinking this notification is by subclassing the desired window's message stream and reacting to a WM_HOTKEY message.
My preference when subclassing is to have the messages dispatched from the generic BAS module sink (by necessity, due to AddressOf limitations) to a companion class that in turn notifies its associated form as needed. The details of this operation could fill an entire column, but luckily, various implementations abound on the Internet, and you can download my solution here. I've wrapped this specific task up in a CHotKey class, which you set up like this:
' Member variables
Private WithEvents m_Hotkey As CHotKey
Private Sub Form_Load()
' Setup instance of hotkey tracking
' class, using Ctrl-1 as the trigger.
Set m_Hotkey = New CHotKey
m_Hotkey.hWnd = Me.hWnd
m_Hotkey.SetHotKey vbKey1, _
vbCtrlMask
End Sub
Each time the class sinks a WM_HOTKEY message, it notifies the form by raising a Hotkey event, and the form then brings itself front and center:
Private Sub m_Hotkey_Hotkey()
' Reposition, and bring forward.
With Me
.WindowState = vbNormal
.Move (Screen.Width - .Width) \ _
2,(Screen.Height - .Height) _
\ 2
.Show
End With
End Sub
You could've wrapped these response details into the companion class just as easily, but they're as likely as not to change from application to application, so I felt they were better left within the individual form.
Back to top
|