private int m_i=0; //用來紀錄hook的handle 以便刪除hook
//安裝hook
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
//刪除hook
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);
//go on 下一個hook鏈表的hook一直到消息所發的設備
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
//得到當前線程id
[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId();
//委託方法
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
//被委託的方法
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
if (nCode>=0)
{
return 1; //返回1就是消息到這裡就 不再往後面傳 , 0或CallNextHookEx 是繼續往後傳消息
}
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
form_load中安裝hook
HookProc Key=new HookProc(KeyboardHookProc);
m_i=SetWindowsHookEx(2,Key,IntPtr.Zero,GetCurrentThreadId()); //2是指線程鍵盤消息,
textBox2.Text=m_i.ToString();
button中刪除hook
UnhookWindowsHookEx(m_i);