在C#和Vista环境下,如果您希望在不在焦点时响应键盘事件,可以使用全局键盘钩子。全局键盘钩子是一种低级键盘输入的拦截方法,允许您在系统级别拦截和处理键盘事件。以下是一个简单的示例,展示了如何在C#中使用全局键盘钩子来监听键盘事件:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class GlobalKeyboardHook
{
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private const int WM_SYSKEYDOWN = 0x0104;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
public event EventHandler<KeyEventArgs> KeyDown;
private IntPtr _hookId = IntPtr.Zero;
private LowLevelKeyboardProc _proc;
public GlobalKeyboardHook()
{
_proc = HookCallback;
}
public void Hook()
{
if (_hookId != IntPtr.Zero) return;
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
_hookId = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
public void Unhook()
{
if (_hookId == IntPtr.Zero) return;
UnhookWindowsHookEx(_hookId);
_hookId = IntPtr.Zero;
}
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
{
int vkCode = Marshal.ReadInt32(lParam);
if (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
{
KeyDown?.Invoke(this, new KeyEventArgs((Keys)vkCode));
}
}
return CallNextHookEx(_hookId, nCode, wParam, lParam);
}
}
public class KeyEventArgs : EventArgs
{
public Keys KeyCode { get; }
public KeyEventArgs(Keys keyCode)
{
KeyCode = keyCode;
}
}
使用这个类,您可以轻松地在C#中实现全局键盘钩子。只需创建一个GlobalKeyboardHook
实例,并为KeyDown
事件添加事件处理程序,即可在系统级别拦截键盘事件。
请注意,全局键盘钩子可能会影响系统性能,因此请谨慎使用。此外,在Vista和更高版本的Windows上,全局键盘钩子需要管理员权限才能正常工作。
领取专属 10元无门槛券
手把手带您无忧上云