Introduction
The HotkeyManager
class makes it easy to set global hotkeys for applications. It is a wrapper class that raises a HotkeyPressed
event whenever a registered hotkey by the HotkeyManager
class is pressed. The class keeps a collection of the registered hotkeys (in a Hotkey
data type), and it is available to the developer through the Hotkeys
property of the HotkeyMananger
object. The HotkeyManager
can be used to register, unregister, or replace (registered by the HotkeyManager
) hotkeys.
Background
To use (create) a HotkeyManager
object, you should pass a valid window (Form
) within the project as an argument to its constructor method. The HotkeyManager
uses two (RegisterHotKey
and UnregisterHotKey
) API methods to register, unregister, and replace hotkeys. All the methods of HotkeyManager
take an argument of type Hotkey
.
On the other hand, the Hotkey
structure has very useful methods too, such as ToString
which returns the string representation of the hotkey (example: Ctrl+H) and many properties (as System.Windows.Forms.Keys
).
Using the code
Here is an example of how to use the HotkeyManager
class:
Public Class Form1
Dim WithEvents hkM As HotkeyManager
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
Me.hkM = New HotkeyManager(Me)
End Sub
Private Sub RegisterButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles RegisterButton.Click
Try
Dim hk As New Hotkey(100, Keys.Alt Or Keys.G)
Me.hkM.RegisterHotKey(hk, True)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) _
Handles Me.FormClosing
If Me.hkM IsNot Nothing Then
Me.hkM.Dispose()
End If
End Sub
Private Sub ReplaceButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ReplaceButton.Click
Try
Dim hk As New Hotkey(100, Keys.Shift Or Keys.B)
Me.hkM.Replace(hk, True)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub UnregisterButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles UnregisterButton.Click
Try
Me.hkM.UnregisterHotKey(100, True)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub hk_HotkeyPressed(ByVal sender As Object, _
ByVal e As HotkeyEventArgs) Handles hkM.HotkeyPressed
Me.HotkeyLabel.Text = e.Hotkey.ToString
End Sub
End Class
History
- Originally posted on 08/05/08.