如何在 WPF 中捕获按键按下?

发布于 2024-10-04 03:35:27 字数 38 浏览 2 评论 0原文

即使我的应用程序没有聚焦,如何在 WPF 中捕获按键按下事件?

How do I capture a key down event in WPF even if my application is not focused?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

空气里的味道 2024-10-11 03:35:27

对我来说,最好的方法是:

public MainWindow()
{
    InitializeComponent();

    CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
}

void CompositionTarget_Rendering(object sender, EventArgs e)
{
    if ((Keyboard.GetKeyStates(Key.W) & KeyStates.Down) > 0)
    {
        player1.walk();
    }
} 

渲染事件每次都运行。

For me, the best way is this:

public MainWindow()
{
    InitializeComponent();

    CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
}

void CompositionTarget_Rendering(object sender, EventArgs e)
{
    if ((Keyboard.GetKeyStates(Key.W) & KeyStates.Down) > 0)
    {
        player1.walk();
    }
} 

The rendering event runs every time.

携君以终年 2024-10-11 03:35:27

全局键盘挂钩会减慢调试速度。

我更喜欢使用这种方法:

  1. 创建 KeyboardListener 类

    公共类KeyboardListener:IDisposable
    {
        私有只读线程键盘线程;
    
        //这里可以放你想要捕获的那些key
        私有只读列表 numericKeys = new List;
        {
            新的KeyState(Key.D0),
            新的 KeyState(Key.D1),
            新的 KeyState(Key.D2),
            新的KeyState(Key.D3),
            新的 KeyState(Key.D4),
            新的KeyState(Key.D5),
            新的KeyState(Key.D6),
            新的 KeyState(Key.D7),
            新的KeyState(Key.D8),
            新的KeyState(Key.D9),
            新的 KeyState(Key.NumPad0),
            新的 KeyState(Key.NumPad1),
            新的 KeyState(Key.NumPad2),
            新的 KeyState(Key.NumPad3),
            新的 KeyState(Key.NumPad4),
            新的 KeyState(Key.NumPad5),
            新的 KeyState(Key.NumPad6),
            新的 KeyState(Key.NumPad7),
            新的 KeyState(Key.NumPad8),
            新的 KeyState(Key.NumPad9),
            新的 KeyState(Key.Enter)
        };
    
        私有布尔 isRunning = true;
    
        公共键盘监听器()
        {
            KeyboardThread = 新线程(StartKeyboardListener) { IsBackground = true };
            键盘线程.Start();
        }
    
        私有无效StartKeyboardListener()
        {
            while(正在运行)
            {
                线程睡眠(15);
                if (应用程序.当前!= null)
                {
                    Application.Current.Dispatcher.Invoke(() =>;
                    {
                        if (Application.Current.Windows.Count > 0)
                        {
                            foreach(numericalKeys 中的 var keyState)
                            {
                                if (Keyboard.IsKeyDown(keyState.Key) && !keyState.IsPressed) //
                                {
                                    keyState.IsPressed = true;
                                    KeyboardDownEvent?.Invoke(null, new KeyEventArgs(Keyboard.PrimaryDevice,PresentationSource.FromDependencyObject(Application.Current.Windows[0]), 0, keyState.Key));
                                }
    
                                if (Keyboard.IsKeyUp(keyState.Key))
                                {
                                    keyState.IsPressed = false;
                                }
                            }
                        }
                    });
                }
            }
        }
    
        公共事件KeyEventHandler KeyboardDownEvent;
    
        /// <摘要>
        /// Состояние клавиши
        /// 
        私有类KeyState
        {
            公钥状态(密钥密钥)
            {
                this.Key = 键;
            }
    
            公钥密钥{获取; }
            公共布尔 IsPressed { 得到;放; }
        }
    
        公共无效处置()
        {
            正在运行=假;
            任务.运行(() =>
            {
                if (keyboardThread != null && !keyboardThread.Join(1000))
                {
                    键盘线程.Abort();
                }
            });
        }
    }
    
  2. 在代码隐藏中(或您需要的地方)订阅KeyboardDownEvent。

    公共分部类 MainWindow : 窗口
    {
        私有 KeyboardListener 监听器;
    
        公共主窗口()
        {
            初始化组件();
        }
    
        private void Window_Loaded(对象发送者, RoutedEventArgs e)
        {
            监听器=新的键盘监听器();
            Listener.KeyboardDownEvent += ListenerOnKeyPressed;
        }
    
        私有无效ListenerOnKeyPressed(对象发送者,KeyEventArgs e)
        {
            // 在此输入您的代码
        }
    
        private void Window_OnUnloaded(对象发送者, RoutedEventArgs e)
        {
            Listener.KeyboardDownEvent -= ListenerOnKeyPressed;
        }
    }
    
  3. 完成

Global keyboard hook can slow down your debugging.

I prefer to use this approach:

  1. Create KeyboardListener class

    public class KeyboardListener : IDisposable
    {
        private readonly Thread keyboardThread;
    
        //Here you can put those keys that you want to capture
        private readonly List<KeyState> numericKeys = new List<KeyState>
        {
            new KeyState(Key.D0),
            new KeyState(Key.D1),
            new KeyState(Key.D2),
            new KeyState(Key.D3),
            new KeyState(Key.D4),
            new KeyState(Key.D5),
            new KeyState(Key.D6),
            new KeyState(Key.D7),
            new KeyState(Key.D8),
            new KeyState(Key.D9),
            new KeyState(Key.NumPad0),
            new KeyState(Key.NumPad1),
            new KeyState(Key.NumPad2),
            new KeyState(Key.NumPad3),
            new KeyState(Key.NumPad4),
            new KeyState(Key.NumPad5),
            new KeyState(Key.NumPad6),
            new KeyState(Key.NumPad7),
            new KeyState(Key.NumPad8),
            new KeyState(Key.NumPad9),
            new KeyState(Key.Enter)
        };
    
        private bool isRunning = true;
    
        public KeyboardListener()
        {
            keyboardThread = new Thread(StartKeyboardListener) { IsBackground = true };
            keyboardThread.Start();
        }
    
        private void StartKeyboardListener()
        {
            while (isRunning)
            {
                Thread.Sleep(15);
                if (Application.Current != null)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        if (Application.Current.Windows.Count > 0)
                        {
                            foreach (var keyState in numericKeys)
                            {
                                if (Keyboard.IsKeyDown(keyState.Key) && !keyState.IsPressed) //
                                {
                                    keyState.IsPressed = true;
                                    KeyboardDownEvent?.Invoke(null, new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromDependencyObject(Application.Current.Windows[0]), 0, keyState.Key));
                                }
    
                                if (Keyboard.IsKeyUp(keyState.Key))
                                {
                                    keyState.IsPressed = false;
                                }
                            }
                        }
                    });
                }
            }
        }
    
        public event KeyEventHandler KeyboardDownEvent;
    
        /// <summary>
        /// Состояние клавиши
        /// </summary>
        private class KeyState
        {
            public KeyState(Key key)
            {
                this.Key = key;
            }
    
            public Key Key { get; }
            public bool IsPressed { get; set; }
        }
    
        public void Dispose()
        {
            isRunning = false;
            Task.Run(() =>
            {
                if (keyboardThread != null && !keyboardThread.Join(1000))
                {
                    keyboardThread.Abort();
                }
            });
        }
    }
    
  2. Subscribe to KeyboardDownEvent in code-behind (or where you need it).

    public partial class MainWindow : Window
    {
        private KeyboardListener listener;
    
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            listener = new KeyboardListener();
            listener.KeyboardDownEvent += ListenerOnKeyPressed;
        }
    
        private void ListenerOnKeyPressed(object sender, KeyEventArgs e)
        {
            // TYPE YOUR CODE HERE
        }
    
        private void Window_OnUnloaded(object sender, RoutedEventArgs e)
        {
            listener.KeyboardDownEvent -= ListenerOnKeyPressed;
        }
    }
    
  3. Done

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文