首页 文章

是否可以在WPF中处理应用程序中的键盘/鼠标事件?

提问于
浏览
3

我意识到这个问题之前可能已被问过,但我找不到这个十年的答案所以我希望答案已经改变并且是“是” .

我正在开发一个没有GUI可以说的应用程序,因此没有“主窗口”来“捕获”鼠标或键盘事件 .

我看过Gma.HookManager项目,但它都是为WinForms编写的,试图让它适应WPF让我想把酗酒作为一种爱好......

是否可以将鼠标/事件处理程序编写到实际的应用程序类中,这样即使应用程序中没有窗口或其他GUI,这些事件也会在按键和/或鼠标事件中被捕获?

1 回答

  • 2

    我写了一个快速的utillity类,用gp在wpf中做你需要的东西 .

    确保在项目中添加对gma库和Windows窗体的引用 . 我很快就对它进行了测试,效果很好,如果您有任何疑问,请告诉我 . 堆栈溢出的新功能btw不确定我是否收到通知 .

    EDIT: 我的解决方案涉及创建我自己的包装器,如果您将围绕gma事件,使用系统KeyInterop类将关键数据从Windows窗体键事件转换为wpf关键数据 .

    这是 class

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Gma.UserActivityMonitor;
    using System.Windows.Input;
    using System.Windows.Forms;
    
    namespace WpfApplicationTest
    {
    public class HookManager
    {
    
        private GlobalEventProvider _provider;
    
        public event EventHandler<HookKeyArgs> KeyDown;
    
        public event EventHandler<HookKeyArgs> KeyUp;
    
        public HookManager()
        {
            _provider = new Gma.UserActivityMonitor.GlobalEventProvider();
    
            _provider.KeyDown += _provider_KeyDown;
            _provider.KeyUp += _provider_KeyUp;
        }
    
        void _provider_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (KeyUp != null)
            {
                KeyUp(this, new HookKeyArgs(convertWinFormsKey(e.KeyData), false, true));
            }
        }
    
        void _provider_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (KeyDown != null)
            {
                KeyDown(this, new HookKeyArgs(convertWinFormsKey(e.KeyData), true, false));
            }
        }
    
        System.Windows.Input.Key convertWinFormsKey(System.Windows.Forms.Keys keyMeta)
        {
            Keys formsKey = keyMeta;
            return KeyInterop.KeyFromVirtualKey((int)formsKey);
        }
    }
    
    public class HookKeyArgs : EventArgs
    {
        public System.Windows.Input.Key KeyPressed {get; private set;}
        public bool IsDown { get; private set; }
    
        public bool IsUp { get; private set; }
    
        public HookKeyArgs(System.Windows.Input.Key keyPressed, bool isDown, bool isUp)
        {
            this.KeyPressed = keyPressed;
            this.IsDown = isDown;
            this.IsUp = isUp;
        }
    
    
    }}
    

    这是使用它的一个例子 .

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
    
            var hookManager = new HookManager();
    
            hookManager.KeyUp += hookManager_KeyUp;
        }
    
        void hookManager_KeyUp(object sender, HookKeyArgs e)
        {
            MessageBox.Show("key pressed: " + e.KeyPressed.ToString());
        }
    }}
    

相关问题