使用SetWindowsHookEx來進行API hooking, 主要目的是攔截windows message (透過sendMessage這個API所發出的訊息), 用來得知不同程序彼此溝通的狀況。
using System.Runtime.InteropServices; // function 宣告 [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); // 被呼叫到的函式 private static int KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam){ // 查一下<a href="http://msdn.microsoft.com/en-us/library/ms644984%28VS.85%29.aspx">msdn文獻</a> // wParam Specifies the virtual-key code of the key that generated the keystroke message // Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag. } // 使用時, new一個function pointer指到KeyboardHookProc m_KbdHookProc = new HookProc(KeyboardHookProc); m_HookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, m_KbdHookProc, GetModuleHandle(curModule.ModuleName), 0);
參考資料
詳細程式碼請見大牛的作法