在C#中使用SetWindowsHookEx函数可以通过PInvoke进行调用。以下是一个简单的示例代码,演示如何使用SetWindowsHookEx函数来监听并拦截鼠标消息。
using System;
using System.Runtime.InteropServices;
namespace SetWindowsHookExExample
{
class Program
{
private delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
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);
private const int WH_MOUSE_LL = 14;
private static IntPtr hookId = IntPtr.Zero;
private static HookProc hookProc;
static void Main(string[] args)
{
hookProc = HookCallback;
hookId = SetHook(hookProc);
Console.WriteLine("Hook installed. Press any key to exit...");
Console.ReadKey();
UnhookWindowsHookEx(hookId);
}
private static IntPtr SetHook(HookProc proc)
{
using (var curProcess = System.Diagnostics.Process.GetCurrentProcess())
using (var curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_MOUSE_LL, proc, Marshal.GetHINSTANCE(curModule), 0);
}
}
private static IntPtr HookCallback(int code, IntPtr wParam, IntPtr lParam)
{
// Intercept and handle mouse messages here
return CallNextHookEx(hookId, code, wParam, lParam);
}
}
}
请注意,这只是一个简单的示例,真实的使用可能需要更多的代码来处理不同类型的消息或事件。您可以根据自己的需求修改和扩展以上示例。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: reference c# 功能强不强呢