I am developing an application that needs to handle all messages sent by the OS to any application.
The code works fine for WH_KEYBOARD_LL only, but fails with WH_GETMESSAGE or WH_CALLWNDPROC
class Program
{
private const int WH_KEYBOARD_LL = 13;
private const int WH_GETMESSAGE = 3;
private const int WH_CALLWNDPROC = 4;
private const int WM_KEYDOWN = 0x0100;
private static HookProc _proc = new HookProc(HookCallback);
private static IntPtr _hookID = IntPtr.Zero;
static void Main(string[] args)
{
TextWriter tw = new StreamWriter("date.txt");
tw.Write(DateTime.Now);
tw.Close();
_hookID = SetHook(_proc);
Application.Run();
UnhookWindowsHookEx(_hookID);
}
private static IntPtr SetHook(HookProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_CALLWNDPROC , proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
private delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(int code, IntPtr wParam, IntPtr lParam)
{
// This method is never called
return CallNextHookEx(_hookID, code, wParam, lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
HookProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
}
Edit:
I think the problem is with the .NET Frame work
Global hooks are not supported in the .NET Framework Except for the WH_KEYBOARD_LL low-level hook and the WH_MOUSE_LL low-level hook, you cannot implement global hooks in the Microsoft .NET Framework.