您可以使用 Nuget 包 MouseKeyHook (GitHub) 在后台监控键盘和鼠标活动。
此代码检测何时按下键:
private IKeyboardMouseEvents _globalHook;
private void Subscribe()
{
if (_globalHook == null)
{
// Note: for the application hook, use the Hook.AppEvents() instead
_globalHook = Hook.GlobalEvents();
_globalHook.KeyPress += GlobalHookKeyPress;
}
}
private static void GlobalHookKeyPress(object sender, KeyPressEventArgs e)
{
Console.WriteLine("KeyPress: \t{0}", e.KeyChar);
}
private void Unsubscribe()
{
if (_globalHook != null)
{
_globalHook.KeyPress -= GlobalHookKeyPress;
_globalHook.Dispose();
}
}
您需要打电话Subscribe()
开始收听和Unsubscribe()
停止收听。显然你需要修改GlobalHookKeyPress()
才能做有用的工作。
我需要这个功能来编写一个实用程序,当按下任何键时,它会打开联想 Thinkpad 上的键盘背光,包括 CTRL(它KeyPress
不会捕捉到)。为此,我不得不监视按键按下。除了我们附加到不同的事件之外,代码是相同的......
_globalHook.KeyDown += GlobalHookOnKeyDown;
并且事件处理程序签名不同:
private static void GlobalHookOnKeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine("KeyDown: \t{0}", e.KeyCode);
}
该库还可以检测特定的组合键和序列。例如:
Hook.GlobalEvents().OnCombination(new Dictionary<Combination, Action>
{
{ Combination.TriggeredBy(Keys.A).Control(), () => { Console.WriteLine("You Pressed CTRL+A"); } },
{ Combination.FromString("Shift+Alt+Enter"), () => { Console.WriteLine("You Pressed FULL SCREEN"); } }
});