在C#中使用全局鼠标、键盘Hook
时间: 2024-05-12 19:14:56 浏览: 188
C# 钩子,实现键盘和鼠标的全部事件全局Hook.(完整源码)
5星 · 资源好评率100%
在C#中使用全局鼠标、键盘Hook需要使用Win32 API来实现,以下是一个简单的示例代码:
```csharp
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace GlobalHookDemo
{
class Program
{
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
private const int WH_KEYBOARD_LL = 13;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
static void Main(string[] args)
{
_hookID = SetHook(_proc);
Console.WriteLine("Global keyboard hook installed.");
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
UnhookWindowsHookEx(_hookID);
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)0x100)
{
int vkCode = Marshal.ReadInt32(lParam);
Console.WriteLine((Keys)vkCode);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
}
}
```
这个示例代码可以监听全局键盘事件并输出键码。如果需要监听鼠标事件,可以使用`SetWindowsHookEx`函数的第一个参数`idHook`设置为`WH_MOUSE_LL`。需要注意的是,全局Hook会影响系统性能,使用时需要谨慎。
阅读全文