安装NuGet包
MouseKeyHook
定义钩子对象
private IKeyboardMouseEvents m_GlobalHook;
初始化钩子并订阅监听事件
//程序钩子,监听当前程序下键鼠操作
//m_GlobalHook = Hook.AppEvents();
//全局钩子,监听所有键鼠操作
m_GlobalHook = Hook.GlobalEvents();
//绑定鼠标点击事件
m_GlobalHook.MouseDownExt += M_GlobalHook_MouseDownExt;
//绑定键盘事件(按下释放后触发)
m_GlobalHook.KeyPress += M_GlobalHook_KeyPress;
监听事件
private void M_GlobalHook_KeyPress(object sender, KeyPressEventArgs e)
{
rtbMessage.AppendText($"{DateTime.Now:yyyy-MM-dd HH:mm:ss}:按下了【{(Keys)e.KeyChar}】键\n");
}
private void M_GlobalHook_MouseDownExt(object sender, MouseEventExtArgs e)
{
string str = string.Empty;
switch (e.Button)
{
case MouseButtons.Left:
str = "左键";
break;
case MouseButtons.None:
str = "无";
break;
case MouseButtons.Right:
str = "右键";
break;
case MouseButtons.Middle:
str = "滑轮";
break;
case MouseButtons.XButton1:
str = "侧边键1";
break;
case MouseButtons.XButton2:
str = "侧边键1";
break;
default:
break;
}
rtbMessage.AppendText($"{DateTime.Now:yyyy-MM-dd HH:mm:ss}:点击了鼠标【{str}】\n");
}
支持监听的键鼠事件
评论区