Home >Backend Development >C++ >How to Register Global Hotkeys in WPF Applications using .NET Framework 3.5?

How to Register Global Hotkeys in WPF Applications using .NET Framework 3.5?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-14 06:48:42933browse

How to Register Global Hotkeys in WPF Applications using .NET Framework 3.5?

Register global hotkeys in WPF application using .NET Framework 3.5

Challenge:

In a WPF application developed using .NET Framework 3.5, you need a way to bind to a specific keypress and determine how to bind to the Windows key.

Solution:

To register global hotkeys in WPF and .NET Framework 3.5, follow these steps:

  1. Import necessary DLLs:
<code class="language-csharp">using System;
using System.Runtime.InteropServices;
using System.Windows.Interop;</code>
  1. Declare helper methods and constants:
<code class="language-csharp">[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, UInt32 fsModifiers, UInt32 vlc);

[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

const int WmHotKey = 0x0312;</code>
  1. Create a HotKey class to manage the registration and use of hotkeys:
<code class="language-csharp">public class HotKey : IDisposable
{
    private bool _disposed;
    private Key _key;
    private KeyModifier _keyModifiers;
    private Action<HotKey> _action;
    private int _id;
    private static Dictionary<int, HotKey> _dictHotKeyToCalBackProc;

    public HotKey(Key k, KeyModifier keyModifiers, Action<HotKey> action, bool register = true)
    {
        _key = k;
        _keyModifiers = keyModifiers;
        _action = action;
        if (register)
            Register();
    }

    public bool Register()
    {
        int virtualKeyCode = KeyInterop.VirtualKeyFromKey(_key);
        _id = virtualKeyCode + ((int)_keyModifiers * 0x10000);
        bool result = RegisterHotKey(IntPtr.Zero, _id, (UInt32)_keyModifiers, (UInt32)virtualKeyCode);

        if (_dictHotKeyToCalBackProc == null)
        {
            _dictHotKeyToCalBackProc = new Dictionary<int, HotKey>();
            ComponentDispatcher.ThreadFilterMessage += ComponentDispatcherThreadFilterMessage;
        }

        _dictHotKeyToCalBackProc.Add(_id, this);
        return result;
    }

    public void Unregister()
    {
        _dictHotKeyToCalBackProc.Remove(_id);
        UnregisterHotKey(IntPtr.Zero, _id);
    }

    private static void ComponentDispatcherThreadFilterMessage(ref MSG msg, ref bool handled)
    {
        if (msg.message == WmHotKey)
        {
            HotKey hotKey;

            if (_dictHotKeyToCalBackProc.TryGetValue((int)msg.wParam, out hotKey))
            {
                hotKey._action.Invoke(hotKey);
                handled = true;
            }
        }
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                Unregister();
            }
            _disposed = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}</code>
  1. Use the HotKey class to register and handle hotkey events. For example:
<code class="language-csharp">// 注册CTRL+SHIFT+F9热键
HotKey hotKey = new HotKey(Key.F9, KeyModifier.Shift | KeyModifier.Ctrl, OnHotKeyHandler);

private void OnHotKeyHandler(HotKey hotKey)
{
    // 按下热键时执行操作
}</code>

This code has made slight adjustments to the original text to make it smoother and easier to read, and has corrected some potential problems, such as adding logic to remove hotkeys from the dictionary in the Unregister method, and improving Dispose method to ensure the correct release of resources. The key logic and code remain unchanged, achieving a pseudo-original version of the original text.

The above is the detailed content of How to Register Global Hotkeys in WPF Applications using .NET Framework 3.5?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn