在整个应用程序中捕获按键

use*_*657 6 c# wpf keypress

有可能,捕获(我想在app.xaml.cs的某个地方)任何键,如果按下打开的窗口?

感谢帮助!

Ada*_*ohl 9

有一个更好的办法。在 MS 论坛上找到了这个。奇迹般有效。

将此代码放入应用程序启动中:

EventManager.RegisterClassHandler(typeof(Window),
     Keyboard.KeyUpEvent,new KeyEventHandler(keyUp), true);

private void keyUp(object sender, KeyEventArgs e)
{
      //Your code...
}
Run Code Online (Sandbox Code Playgroud)


khe*_*ang 5

你可以使用像这个gist这样的东西来注册一个全局钩子.在应用程序运行时按下给定键时,它将触发.你可以在你的App班级中使用它,如下所示:

public partial class App
{
    private HotKey _hotKey;

    protected override void OnActivated(EventArgs e)
    {
        base.OnActivated(e);
        RegisterHotKeys();
    }

    protected override void OnExit(ExitEventArgs e)
    {
        base.OnExit(e);
        UnregisterHotKeys();
    }

    private void RegisterHotKeys()
    {
        if (_hotKey != null) return;

        _hotKey = new HotKey(ModifierKeys.Control | ModifierKeys.Shift, Key.V, Current.MainWindow);
        _hotKey.HotKeyPressed += OnHotKeyPressed;
    }

    private void UnregisterHotKeys()
    {
        if (_hotKey == null) return;

        _hotKey.HotKeyPressed -= OnHotKeyPressed;
        _hotKey.Dispose();
    }

    private void OnHotKeyPressed(HotKey hotKey)
    {
        // Do whatever you want to do here
    }
}
Run Code Online (Sandbox Code Playgroud)