Question

I'm trying to catch the event of creating/destroying the specified window of another application. For this purpose I set WM_SHELLHOOK.

Here is siplified code from my WPF application:

public delegate IntPtr ProcDelegate(int hookCode, IntPtr wParam, IntPtr lParam);

[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(
    int hookId, ProcDelegate handler, IntPtr hInstance, uint threadId);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);

private void buttonClick(object sender, RoutedEventArgs e)
{
    IntPtr hookHandler;

    using (Process curProcess = Process.GetCurrentProcess())
    using (ProcessModule curModule = curProcess.MainModule)
    {
        var moduleHandle = GetModuleHandle(curModule.ModuleName);
        hookHandler = SetWindowsHookEx(
            10 /*WH_SHELL*/, shellHookHandler, moduleHandle, 0);
    }

    if (hookHandler == IntPtr.Zero)
    {
        // Get here error 1428 (ERROR_HOOK_NEEDS_HMOD) -
        // "Cannot set nonlocal hook without a module handle."
        throw new Exception(Marshal.GetLastWin32Error().ToString());
    }
}

private IntPtr shellHookHandler(int hookCode, IntPtr wParam, IntPtr lParam)
{
    // Some code...
    return IntPtr.Zero;
}

The problem is that SetWindowsHookEx always returns 0 and last error is

1428 (ERROR_HOOK_NEEDS_HMOD) Cannot set nonlocal hook without a module handle.

I have looked another related questions. When I set hook for mouse, keyboard, etc - everything OK.

Please, point me how to fix this error. Thanks.

Was it helpful?

Solution

The MSDN documentation for hooks says "If the application installs a hook procedure for a thread of a different application, the procedure must be in a DLL."

This is because your DLL is loaded into the address-space of the other application; you then need to find some mechanism (e.g. a memory-mapped file) to pass information to your main application.

However, contrary to most of the documentation (it is mentioned here), keyboard and mouse hooks work without a DLL. That's why they worked for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top