在C#中设置和使用全局钩子通常涉及到使用Windows API函数,这需要P/Invoke
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class GlobalHook
{
public const int WH_KEYBOARD_LL = 13;
public const int WM_KEYDOWN = 0x0100;
public const int WM_KEYUP = 0x0101;
public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, GlobalHook.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 class GlobalHook
{
// ... 其他代码 ...
private IntPtr _hookID = IntPtr.Zero;
private GlobalHook.LowLevelKeyboardProc _proc;
public void SetHook()
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
_proc = HookCallback;
_hookID = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
public void UnsetHook()
{
UnhookWindowsHookEx(_hookID);
}
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_KEYUP))
{
int vkCode = Marshal.ReadInt32(lParam);
Console.WriteLine((Keys)vkCode);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
}
public static void Main()
{
GlobalHook globalHook = new GlobalHook();
globalHook.SetHook();
Application.Run(); // 保持程序运行,直到用户关闭它
globalHook.UnsetHook();
}
请注意,全局钩子可能会影响系统性能,因此请谨慎使用。此外,这种方法可能不适用于所有场景,特别是在某些安全策略严格的环境中。在实际应用中,请确保遵循最佳实践和适当的安全措施。