C# WinForm鍵盤鉤子
IntPtr MyHookProc(int code, IntPtr wparam, IntPtr lparam)
{
if( code < 0 ) return CallNextHookEx(_nextHookPtr,code, wparam, lparam); //返回,讓後面的程序處理該消息
return (IntPtr) 1; //直接返回了,該消息就處理結束
}
實現過程:
1、新建壹個C#的WindowsApplication
2、在Form1中,添加下面壹些變量:
internal enum HookType //枚舉,鉤子的類型
{
//MsgFilter = -1,
//JournalRecord = 0,
//JournalPlayback = 1,
Keyboard = 2,
//GetMessage = 3,
//CallWndProc = 4,
//CBT = 5,
//SysMsgFilter = 6,
//Mouse = 7,
//Hardware = 8,
//Debug = 9,
//Shell = 10,
//ForegroundIdle = 11,
//CallWndProcRet = 12,
//KeyboardLL = 13,
//MouseLL = 14,
};
IntPtr _nextHookPtr; //記錄Hook編號
3、在Form1中引入必須的API
[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId(); //取得當前線程編號的API
[DllImport("User32.dll")]
internal extern static void UnhookWindowsHookEx(IntPtr handle); //取消Hook的API
[DllImport("User32.dll")]
internal extern static IntPtr SetWindowsHookEx(int idHook, [MarshalAs(UnmanagedType.FunctionPtr)] HookProc lpfn, IntPtr hinstance, int threadID); //設置Hook的API
[DllImport("User32.dll")]
internal extern static IntPtr CallNextHookEx(IntPtr handle, int code, IntPtr wparam, IntPtr lparam); //取得下壹個Hook的API
4、聲明壹個實現的委托
internal delegate IntPtr HookProc(int code, IntPtr wparam, IntPtr lparam);
5、添加自己的Hook處理過程
IntPtr MyHookProc(int code, IntPtr wparam, IntPtr lparam)
{
if( code < 0 ) return CallNextHookEx(_nextHookPtr,code, wparam, lparam); //返回,讓後面的程序處理該消息
if( wparam.ToInt32() <96 || wparam.ToInt32()>105 || wparam.ToInt32()<>13 )
//如果用戶輸入的不是0-9和回車就攔截
{
return (IntPtr) 1; //直接攔截,該消息就處理結束了
}
else
{
return IntPtr.Zero; //返回,讓後面的程序處理該消息
}
}
6、添加加入Hook鏈和從Hook鏈中取消的函數
public void SetHook()
{
if( _nextHookPtr != IntPtr.Zero ) //已經勾過了
return;
HookProc myhookProc = new HookProc(MyHookProc); //聲明壹個自己的Hook實現函數的委托對象
_nextHookPtr = SetWindowsHookEx((int)HookType.Keyboard, myhookProc , IntPtr.Zero , GetCurrentThreadId()); //加到Hook鏈中
}
public void UnHook()
{
if( _nextHookPtr != IntPtr.Zero )
{
UnhookWindowsHookEx(_nextHookPtr); //從Hook鏈中取消
_nextHookPtr = IntPtr.Zero;
}
}
7、在Form1的Load事件中添加 SetHook() , 在Form1的closing 事件中添加 UnHook()
private void Form1_Load(object sender, System.EventArgs e)
{
SetHook();
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
UnHook();
}