最近做一个项目,需要截获特定应用程序里鼠标和键盘的消息事件。之前本人对windows底层的消息处理机制并不熟悉,通过学习知道钩子机制可以帮助我们截获处理windows消息或特定事件,现将本人所掌握的知识内容总结如下:
1.调用windows底层API,定义winAPI类
using System.Runtime.InteropServices;
public class WinApi
{
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct
{
public POINT pt;
public int hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public class KeyboardHookStruct
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
//安装钩子
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);