在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);
}
}
}
請注意,這只是一個簡單的示例,真實的使用可能需要更多的代碼來處理不同類型的消息或事件。您可以根據自己的需求修改和擴展以上示例。