How to register hotkeys for your application in

This article is for how to register hotkeys for your application in


How to perform various task or operation in application while it is not in focus (such as being minimized to tray). For example if we have a data entry application that is running in the system tray. When the user click on ALT + N keys, application will be display on the screen. and when user click on ALT + C, form will be hide and goes to system tray.

Idea behind the problem:

We can not use the Key press or key down event when the application has no focus. So we will register the hot keys (ALT + N and ALT + C) in we will register ALT + N for showing the application and ALT + C fro hiding the application.

Code Example

Start a window application and add a form named Form1. Add some textbox and label controls and add a notify icon control on the Form1. Set the Form1’s property ShowinTaskbar to false and register the both hotkeys on the form1’s load event with the help of RegisterHotKey() function of the USer32.dll windows api.

Imports System.Runtime.InteropServices
Public Class Form1
    Public Const KEY_ALT As Integer = &H1
    Public Const _HOTKEY As Integer = &H312
    <DllImport("User32.dll")> _
    Public Shared Function RegisterHotKey(ByVal hwnd As IntPtr, _
                        ByVal id As Integer, ByVal fsModifiers As Integer, _
                        ByVal vk As Integer) As Integer
    End Function
    <DllImport("User32.dll")> _
    Public Shared Function UnregisterHotKey(ByVal hwnd As IntPtr, _
                        ByVal id As Integer) As Integer
    End Function
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        RegisterHotKey(Me.Handle, 1, KEY_ALT, Keys.N)
        RegisterHotKey(Me.Handle, 2, KEY_ALT, Keys.C)
    End Sub
    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = _HOTKEY Then
            Dim id As IntPtr = m.WParam
            Select Case (id.ToString)
                Case "1"
                    Me.WindowState = FormWindowState.Normal
                Case "2"
                    Me.WindowState = FormWindowState.Minimized
            End Select
        End If
    End Sub
    Private Sub Form1_FormClosing(ByVal sender As System.Object, _
                        ByVal e As System.Windows.Forms.FormClosingEventArgs) _
                        Handles MyBase.FormClosing
        UnregisterHotKey(Me.Handle, 1)
        UnregisterHotKey(Me.Handle, 2)
    End Sub
End Class

The above code will works as when user click ALT + C, the application will be hide and got to system tray, and when user press ALT + N, application will be appear.