110,953
社区成员
发帖
与我相关
我的任务
分享
public class MyHook
{
const int WH_GETMESSAGE=3;
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int hookType,HookProc hookProc,IntPtr instance,int threadID);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr hookHandle, int nCode, IntPtr wParam, IntPtr lParam);
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
static IntPtr hookHandle=IntPtr.Zero;//钩子的句柄
/// <summary>
/// 安装钩子
/// </summary>
/// <returns></returns>
public static bool SetHook()
{
IntPtr h=Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]);
hookHandle = SetWindowsHookEx(WH_GETMESSAGE,new HookProc(HookCallBack),h,0);
if(hookHandle==IntPtr.Zero)
{
System.Windows.Forms.MessageBox.Show("安装失败了");
return false;
}
return true;
}
public static IntPtr HookCallBack(int nCode,IntPtr wParam,IntPtr lParam)
{
System.Diagnostics.Debug.WriteLine("有消息近来了");//只会执行一次
if(nCode < 0)
{
CallNextHookEx(hookHandle,nCode,wParam,lParam);
return IntPtr.Zero;
}
else
{
return CallNextHookEx(hookHandle,nCode,wParam,lParam);
}
}
}