|
|
Title | Install a hotkey that minimizes the window with the focus |
Keywords | hotkey, minimize, focus window, accelerator, install hotkey, RegisterHotKey |
Categories | Utilities, Windows, API, Tips and Tricks |
|
|
A hotkey is a key combination that you can use to trigger an action anywhere in Windows.
When the form loads, use the RegisterHotKey API function to install the hotkey (in this example, Alt-F10). Then subclass to watch for the WM_HOTKEY message.
|
|
Private Sub Form_Load()
' Register the hotkey.
If RegisterHotKey(hWnd, HOTKEY_ID, _
MOD_ALT, VK_F10) = 0 _
Then
MsgBox "Error registering hotkey."
Unload Me
End If
' Subclass the TextBox to watch for
' WM_HOTKEY messages.
OldWindowProc = SetWindowLong( _
hWnd, GWL_WNDPROC, _
AddressOf NewWindowProc)
End Sub
|
|
When the new WindowProc sees the WM_HOTKEY message, it calls the form's public Hotkey subroutine.
|
|
' Look for the WM_HOTKEY message.
Public Function NewWindowProc(ByVal hWnd As Long, ByVal Msg _
As Long, ByVal wParam As Long, ByVal lParam As Long) As _
Long
Const WM_NCDESTROY = &H82
Const WM_HOTKEY = &H312
' If we're being destroyed,
' restore the original WindowProc and
' unregister the hotkey.
If Msg = WM_NCDESTROY Then
SetWindowLong _
hWnd, GWL_WNDPROC, _
OldWindowProc
UnregisterHotKey hWnd, HOTKEY_ID
End If
' See if this is the WM_HOTKEY message.
If Msg = WM_HOTKEY Then Form1.Hotkey
' Process the message normally.
NewWindowProc = CallWindowProc( _
OldWindowProc, hWnd, Msg, wParam, _
lParam)
End Function
|
|
When the program receives the Hotkey event, it uses the GetForegroundWindow API function to find the window in the foreground. It then call SetWindowPlacement to minimize the window.
|
|
' We got the hotkey.
Public Sub Hotkey()
Dim active_hwnd As Long
Dim wp As WINDOWPLACEMENT
' Get the active window's handle.
active_hwnd = GetForegroundWindow()
' Get the window's current placement information.
wp.length = Len(wp)
GetWindowPlacement active_hwnd, wp
' Minimize it.
wp.showCmd = SW_SHOWMINIMIZED
' Perform the action.
SetWindowPlacement active_hwnd, wp
End Sub
|
|
|
|
|
|