Click here to Skip to main content
6,597,576 members and growing! (23,546 online)
Email Password   helpLost your password?
Languages » VB.NET » General     Intermediate License: The Code Project Open License (CPOL)

.NET system wide hotkey component

By Duncan Edwards Jones

A component to respond to a hotkey combination, system-wide.
VB.NET 1.0, .NET 1.1, Win2K, WinXP, Win2003VS.NET2003, Dev
Posted:15 Jun 2003
Updated:18 Apr 2006
Views:138,025
Bookmarked:87 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
22 votes for this article.
Popularity: 5.55 Rating: 4.13 out of 5
3 votes, 13.6%
1
1 vote, 4.5%
2
3 votes, 13.6%
3
5 votes, 22.7%
4
10 votes, 45.5%
5

Introduction

A system wide hotkey is a key combination that fires a specific event regardless of which application has the input focus. For example, if you press WIN+E, then a new instance of Explorer is fired up, or if you press CTRL+PRINTSCREEN the currently active window is screen printed to the clipboard.

The Win32 API has a couple of calls which are used to set up and respond to hotkeys - specifically RegisterHotKey and UnregisterHotKey which you declare in VB.NET thus:

<DllImport("user32", EntryPoint:="RegisterHotKey", _
          SetLastError:=True, _
          ExactSpelling:=True, _
          CallingConvention:=CallingConvention.StdCall)> _
Public Function RegisterHotkey(ByVal hwnd As IntPtr, _
           ByVal Id As Int32, _
           <MarshalAs(UnmanagedType.U4)> ByVal fsModifiers As Int32, _
           <MarshalAs(UnmanagedType.U4)> ByVal vkey As Int32) As Boolean

End Function

<DllImport("user32", EntryPoint:="UnregisterHotKey", _
SetLastError:=True, _
ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Function UnregisterHotkey(ByVal hwnd As Int32, _
                            ByVal Id As Int32) As Boolean

End Function

After a hotkey has been registered by the API call RegisterHotkey, then whenever the key combination specified is pressed, a WM_HOTKEY Windows message is sent to the window passed to it in the hwnd parameter.

Specifying the key combination

The key that triggers the event is defined by the two parameters fsModifiers and vKey.

fsModifiers is a value which tells the operating system, which modifier keys are included in the hotkey combination - i.e. Alt, Ctrl, Shift or Win key. This value is made by a combination of the following flags:

Public Enum HotkeyModifierFlags
    MOD_ALT = &H1
    MOD_CONTROL = &H2
    MOD_SHIFT = &H4
    MOD_WIN = &H8
End Enum

Thus, for example, if you want a hotkey which is CTRL+ALT+C, then the modifier would be MOD_ALT + MOD_CONTROL.

The vKey parameter is the virtual key code of the key that goes along with the modifier to define the hot key combination.

Specifying a unique hotkey ID

The id parameter is used to differentiate between multiple hotkeys that can be received by a given window. To ensure that we are dealing with an unique ID, I use the API call GlobalAddAtom to return the id. This is declared thus:

<DllImport("kernel32", EntryPoint:="GlobalAddAtom", _
SetLastError:=True, _
ExactSpelling:=False)> _
Public Function GlobalAddAtom(<MarshalAs(UnmanagedType.LPTStr)> _
                ByVal lpString As String) As Int32

End Function

Creating a window to listen for the WM_HOTKEY message

The final parameter is a window handle to listen for the WM_HOTKEY message. Here there are two options - either pass in the handle of an existing window and subclass it's WndProc to look out for the message or create a new invisible window specifically to listen for the message.

The second option is achieved by creating a new class that derives from System.Windows.Forms.NativeWindow thus:

Public Class GlobalHotkeyListener
    Inherits NativeWindow

#Region "Private member variables"
    Private windowHandle As Integer
    Private mwh As ManualResetEvent
#End Region

    Public Sub New(ByVal Id As Int32, _
              ByVal fsModifiers As Int32, _
              ByVal vkey As Int32, _
              ByRef wh As ManualResetEvent)

        '\\ Get a local copy of the wait handle


        mwh = wh
        Dim cp As CreateParams = New CreateParams()

        ' Fill in the CreateParams details.

        cp.Caption = ""
        cp.ClassName = "STATIC"

        ' Set the position on the form

        cp.X = 0
        cp.Y = 0
        cp.Height = 0
        cp.Width = 0

        '\\ Set the style and extended style flags

        cp.Style = WindowStyleBits.WS_MINIMIZE
        cp.ExStyle = WindowStyleExtendedBits.WS_EX_NOACTIVATE

        ' Create the actual window

        Me.CreateHandle(cp)

        Try
            If Not RegisterHotkey(MyBase.Handle, _
                        Id, fsModifiers, vkey) Then
                Throw New Win32Exception()
            End If
        Catch e As Exception
            System.Diagnostics.Debug.WriteLine(e.ToString)
        End Try
    End Sub

And the listening for the WM_HOTKEY is done thus:

<System.Security.Permissions._
                 PermissionSetAttribute(System.Security.Permissions_
                 .SecurityAction.Demand, Name:="FullTrust")> _
    Protected Overrides Sub WndProc(ByRef m As Message)
        ' Listen for messages that are sent to the 

        ' button window. Some messages are sent

        ' to the parent window instead of the button's window.


        Select Case (m.Msg)
            Case WM_HOTKEY
                ' Respond to the hotkey message (asynchronously??)

                If Not mwh Is Nothing Then
                    mwh.Set()
                End If
        End Select

        MyBase.WndProc(m)
    End Sub

Future improvements

Ideally this control should have a UIEditor derived class to allow the selection of the key combination.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Duncan Edwards Jones


Member
Microsoft MVP 2006, 2007
Visual Basic .NET
Occupation: Software Developer (Senior)
Location: Ireland Ireland

Other popular VB.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 49 (Total in Forum: 49) (Refresh)FirstPrevNext
GeneralI'm very thankful PinmemberPhani Pradeep5:39 16 Mar '09  
QuestionPrintScreen Pinmembermahone7:46 8 Jan '09  
GeneralWhere do I declare the hotkey combination Pinmemberisgrom5:21 29 Oct '07  
Newsyou can instead it with this PinmemberWan--Vevi16:39 31 Aug '07  
GeneralRe: you can instead it with this PinmemberDuncan Edwards Jones11:16 1 Sep '07  
QuestionMultiple hotkeys Pinmemberstupid489:11 1 Jun '07  
AnswerRe: Multiple hotkeys Pinmembermahone11:50 13 Jan '09  
QuestionDouble Tab Hotkey PinmemberHakunaMatada3:00 16 May '07  
GeneralMCLHotkey.xml Pinmembermoa7723:04 18 Jan '07  
QuestionHotkey as Windows service Pinmembermoa779:21 14 Dec '06  
AnswerRe: Hotkey as Windows service PinmemberDuncan Edwards Jones13:08 14 Dec '06  
QuestionRe: Hotkey as Windows service Pinmembermoa7723:20 14 Dec '06  
GeneralRe: Hotkey as Windows service Pinmembermoa7711:51 17 Dec '06  
GeneralRe: Hotkey as Windows service Pinmemberkraghavk23:00 23 Jul '07  
GeneralBuild HotKeyTest for install Pinmembermoa771:30 18 Jul '06  
GeneralRe: Build HotKeyTest for install PinmemberDuncan Edwards Jones2:02 18 Jul '06  
GeneralRe: Build HotKeyTest for install Pinmembermoa772:45 18 Jul '06  
GeneralRe: Build HotKeyTest for install PinmemberDuncan Edwards Jones3:49 18 Jul '06  
GeneralRe: Build HotKeyTest for install Pinmembermoa773:59 18 Jul '06  
GeneralHow to Use it? PinmemberBarrin8622:46 13 Jun '06  
GeneralMissing Test App PinmemberJ Benjamin9:22 29 Aug '05  
GeneralRe: Missing Test App PinmemberDuncan Edwards Jones1:24 19 Sep '05  
GeneralTest Application Missing PinmemberMayank Gupta15:58 31 Mar '05  
GeneralRe: Test Application Missing Pinmemberjahooper11:03 20 Apr '05  
GeneralRe: Test Application Missing Pinmemberbayter11:49 5 Jul '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 18 Apr 2006
Editor: Smitha Vijayan
Copyright 2003 by Duncan Edwards Jones
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project