Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Support Forum
Download Visual Studio Add-In

Terms of Use
Privacy Policy
registerhotkey (user32)
 
.
Summary
Defines a system-wide hot key.

C# Signature:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk);

VB Signature:

Declare Function RegisterHotKeyaspx Lib "user32.dll" (TODO) As TODO

User-Defined Types:

None.

Alternative Managed API:

Do you know one? Please contribute it!

Notes:

None.

Tips & Tricks:

Please add some!

Sample Code:

Here is a helper class for easily adding a hotkey to WPF Windows.

Usage:

    /// <summary>
    /// Id's to disambiguate multiple hotkey registrations
    /// </summary>
    uint hotKey1, hotKey2;

    // --------------------------------------------------------------------------
    /// <summary>
    /// Once we have a window handle, register for hot keys
    /// </summary>
    // --------------------------------------------------------------------------
    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        _hotKeys = new HotKeyHelper(this, HandleHotKey);
        hotKey1 = _hotKeys.ListenForHotKey(System.Windows.Forms.Keys.F8, HotKeyModifiers.Control);
        hotKey2 = _hotKeys.ListenForHotKey(System.Windows.Forms.Keys.F9, HotKeyModifiers.WindowsKey | HotKeyModifiers.Shift);
    }

    // --------------------------------------------------------------------------
    /// <summary>
    /// Hotkey handler.  The keyId is the return value from ListenForHotKey()
    /// </summary>
    // --------------------------------------------------------------------------
    void HandleHotKey(int keyId)
    {
        if (keyId == hotKey1)
        {
        // first hotkey was pressed
        }
        else if (keyId == hotKey2)
        {
        // second hotkey was pressed
        }
    }

Helper class:

    /// <summary>
    /// Simpler way to expose key modifiers
    /// </summary>
    [Flags]
    public enum HotKeyModifiers
    {
    Alt = 1,        // MOD_ALT
    Control = 2,    // MOD_CONTROL
    Shift = 4,      // MOD_SHIFT
    WindowsKey = 8,     // MOD_WIN
    }

    // --------------------------------------------------------------------------
    /// <summary>
    /// A nice generic class to register multiple hotkeys for your app
    /// </summary>
    // --------------------------------------------------------------------------
    public class HotKeyHelper : IDisposable
    {
    // Required interop declarations for working with hotkeys
    [DllImport("user32", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool RegisterHotKey(IntPtr hwnd, int id, uint fsModifiers, uint vk);
    [DllImport("user32", SetLastError = true)]
    public static extern int UnregisterHotKey(IntPtr hwnd, int id);
    [DllImport("kernel32", SetLastError = true)]
    public static extern short GlobalAddAtom(string lpString);
    [DllImport("kernel32", SetLastError = true)]
    public static extern short GlobalDeleteAtom(short nAtom);

    public const int WM_HOTKEY = 0x312;

    /// <summary>
    /// The unique ID to receive hotkey messages
    /// </summary>
    public short HotkeyID { get; private set; }

    /// <summary>
    /// Handle to the window listening to hotkeys
    /// </summary>
    private IntPtr _windowHandle;

    /// <summary>
    /// Callback for hot keys
    /// </summary>
    Action<int> _onHotKeyPressed;

    // --------------------------------------------------------------------------
    /// <summary>
    /// ctor
    /// </summary>
    // --------------------------------------------------------------------------

    public HotKeyHelper(Window handlerWindow, Action<int> hotKeyHandler)
    {
        _onHotKeyPressed = hotKeyHandler;

        // Create a unique Id for this class in this instance
        string atomName = Thread.CurrentThread.ManagedThreadId.ToString("X8") + this.GetType().FullName;
        HotkeyID = GlobalAddAtom(atomName);

        // Set up the hook to listen for hot keys
        _windowHandle = new WindowInteropHelper(handlerWindow).Handle;
        if(_windowHandle == null)
        {
        throw new ApplicationException("Cannot find window handle.  Try calling this on or after OnSourceInitialized()");
        }
        var source = HwndSource.FromHwnd(_windowHandle);
        source.AddHook(HwndHook);
    }

    // --------------------------------------------------------------------------
    /// <summary>
    /// Intermediate processing of hotkeys
    /// </summary>
    // --------------------------------------------------------------------------
    private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == WM_HOTKEY && wParam.ToInt32() == HotkeyID)
        {
        _onHotKeyPressed?.Invoke(lParam.ToInt32());
        handled = true;
        }
        return IntPtr.Zero;
    }

    // --------------------------------------------------------------------------
    /// <summary>
    /// Tell what key you want to listen for.  Returns an id representing
    /// this particular key combination.  Use this in your handler to
    /// disambiguate what key was pressed.
    /// </summary>
    // --------------------------------------------------------------------------
    public uint ListenForHotKey(Keys key, HotKeyModifiers modifiers)
    {
        RegisterHotKey(_windowHandle, HotkeyID, (uint)modifiers, (uint)key);
        return (uint)modifiers | (((uint)key) << 16);
    }

    // --------------------------------------------------------------------------
    /// <summary>
    /// Stop listening for hotkeys
    /// </summary>
    // --------------------------------------------------------------------------
    private void StopListening()
    {
        if (this.HotkeyID != 0)
        {
        UnregisterHotKey(_windowHandle, HotkeyID);
        // clean up the atom list
        GlobalDeleteAtom(HotkeyID);
        HotkeyID = 0;
        }
    }

    // --------------------------------------------------------------------------
    /// <summary>
    /// Dispose
    /// </summary>
    // --------------------------------------------------------------------------
    public void Dispose()
    {
        StopListening();
    }
    }

Documentation

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Find References
Show Printable Version
Revisions