Archive for the 'Hot Key' Tag

VB Net - Global Hotkey

Private Declare Function RegisterHotKey Lib “user32″ (ByVal hwnd As IntPtr, ByVal id As Integer, ByVal fsModifiers As Integer, ByVal vk As Integer) As Integer
Private Declare Function UnregisterHotKey Lib “user32″ (ByVal hwnd As IntPtr, ByVal id As Integer) As Integer
Private Declare Function GlobalAddAtom Lib “kernel32″ Alias “GlobalAddAtomA” (ByVal lpString As String) As Short
Private Declare Function GlobalDeleteAtom Lib “kernel32″ (ByVal nAtom As Short) As Short
Private Const MOD_ALT As Integer = 1
Private Const MOD_CONTROL As Integer = 2
Private Const MOD_SHIFT As Integer = 4
Private Const MOD_WIN As Integer = 8
Private Const MOD_NONE As Integer = 0
Private Const WM_HOTKEY As Integer = &H312
Dim hotkeyID As Short

Sub RegisterGHK(ByVal hotkey As Keys, ByVal modifiers As Integer)
Try
Dim atomName As String = Process.GetCurrentProcess.Id.ToString(”X8″) & Me.Name
hotkeyID = GlobalAddAtom(atomName)
If hotkeyID = 0 Then
Throw New Exception(”Unable to generate unique hotkey ID. Error code: ” & System.Runtime.InteropServices.Marshal.GetLastWin32Error().ToString)
End If

If RegisterHotKey(Me.Handle, hotkeyID, modifiers, CInt(hotkey)) = 0 Then
Throw New Exception(”Unable to register hotkey. Error code: ” & System.Runtime.InteropServices.Marshal.GetLastWin32Error.ToString)
End If
Catch ex As Exception
UnregisterGHK()
End Try
End Sub

Sub UnregisterGHK()
If Me.hotkeyID <> 0 Then
UnregisterHotKey(Me.Handle, hotkeyID)
GlobalDeleteAtom(hotkeyID)
hotkeyID = 0
End If
End Sub

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
MyBase.WndProc(m)
If m.Msg = WM_HOTKEY Then
Me.Activate()
MessageBox.Show(”Hotkey has been pressed”)
End If

Read more »