我编写了一个快速实用程序类来使用 gma 在 wpf 中完成您需要的工作。
确保在项目中添加对 gma 库和 windows 窗体的引用。我很快测试了它,它运行良好,如果您有任何问题,请告诉我。新的堆栈溢出顺便说一句不确定我是否收到通知。
编辑:如果您将围绕 gma 事件创建我自己的包装器,我的解决方案包括使用系统 KeyInterop 类将密钥数据从 windows 窗体键事件转换为 wpf 键数据。
这是课程
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());
}
}}