Note that there are some explanatory texts on larger screens.

plurals
  1. POSetWindowsHookEx seems not working for me in C# (WH_KEYBOARD_LL, global)
    text
    copied!<p>My application should perform some action whenever user pressed certain keys in windows. </p> <p>Calling <a href="http://msdn.microsoft.com/en-us/library/ms644990%28VS.85%29.aspx" rel="nofollow"><code>SetWindowsHookEx</code></a> with <code>WH_KEYBOARD_LL</code> option seems to be standard way to achieve this. However in my case something is clearly wrong and callback in not fired.</p> <p>Main method of my debugging console application:</p> <pre><code>static void Main(string[] args) { IntPtr moduleHandle = GetCurrentModuleHandle(); IntPtr hookHandle = IntPtr.Zero; try { User32.HookProc hook = (nCode, wParam, lParam) =&gt; { // code is never called :-( if (nCode &gt;= 0) { Console.WriteLine("{0}, {1}", wParam.ToInt32(), lParam.ToInt32()); } return User32.CallNextHookEx(hookHandle, nCode, wParam, lParam); }; hookHandle = User32.SetWindowsHookEx(User32.WH_KEYBOARD_LL, hook, moduleHandle, 0); Console.ReadLine(); // } finally { if (hoodHandle != IntPtr.Zero) { var unhooked = User32.UnhookWindowsHookEx(hookHandle); Console.WriteLine(unhooked); // true hookHandle = IntPtr.Zero; } } } </code></pre> <p>GetCurrentModuleHandle method:</p> <pre><code>private static IntPtr GetCurrentModuleHandle() { using (var currentProcess = Process.GetCurrentProcess()) using (var mainModule = currentProcess.MainModule) { var moduleName = mainModule.ModuleName; return Kernel32.GetModuleHandle(moduleName); } } </code></pre> <p>Imports from <code>user32.dll</code> and <code>kernel32.dll</code>:</p> <pre><code>public static class User32 { public const int WH_KEYBOARD_LL = 13; public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnhookWindowsHookEx(IntPtr hhk); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); } public static class Kernel32 { [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr GetModuleHandle(string lpModuleName); } </code></pre> <p>Do you have any idea what I is my problem?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload