0

I try to understand windows hooks in .NET. I want to listen for pressed keys (global). I understand what the first and second parameters of SetWindowsHooks mean. The first parameter specifies the type of hook, e.g. 2 for WH_KEYBOARD and the second the callback handler, e.g. which function should be called if the event occurs.

And if I set the the last parameter to 0 I can intercept the events for all threads in the system.

But why (and how) I must specify the third parameter? I try to hook for WH_Keyboard (type 2) in my console application in this form:

hookID = SetWindowsHookEx((int) WH_TYPE.WH_KEYBOARD, hp,IntPtr.Zero, 0);

It doesn't work. Because IntPtr.Zero is not valid in this context. Can someone explain what the third parameter means and how I can specify a valid one so my console application can react to (global) WH_KEYBOARD events?

Thanks in advance

knowledge
  • 941
  • 1
  • 11
  • 26
  • 3
    It is not the kind of hook you can use in C# code, it requires DLL injection. Use WH_KEYBOARD_LL instead. Requires a message loop which a console mode app does not have, lots of libraries out there provide you with one. Simply search Nuget for "keyboard hook". – Hans Passant May 08 '17 at 11:39
  • So when I should use WH_KEYBOARD? And why and how I must specify hInstance (third parameter) if I want to use it – knowledge May 08 '17 at 11:48
  • See Hans' answer at [difference between WH_KEYBOARD and WH_KEYBOARD_LL?](http://stackoverflow.com/questions/10718009/difference-between-wh-keyboard-and-wh-keyboard-ll) – stuartd May 08 '17 at 11:52
  • @HansPassant Thanks for your answer. If I call "Application.Run()" in my console application the hook procedure is called. Why Application.Run() creates a message loop? And why is such a loop not callable from a "pure" console application? – knowledge May 08 '17 at 14:16

0 Answers0