在C#中使用SetWindowsHookEx函數(shù)可以通過PInvoke進(jìn)行調(diào)用。以下是一個簡單的示例代碼,演示如何使用SetWindowsHookEx函數(shù)來監(jiān)聽并攔截鼠標(biāo)消息。
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);
}
}
}
請注意,這只是一個簡單的示例,真實的使用可能需要更多的代碼來處理不同類型的消息或事件。您可以根據(jù)自己的需求修改和擴(kuò)展以上示例。