简体   繁体   English

WPF应用程序中的全局Shell钩子

[英]Global shell hook in WPF application

I'm trying to catch the event of creating/destroying the specified window of another application. 我正在尝试捕获创建/销毁另一个应用程序的指定窗口的事件。 For this purpose I set WM_SHELLHOOK . 为此,我设置了WM_SHELLHOOK

Here is siplified code from my WPF application: 这是我的WPF应用程序中的简化代码:

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 问题是SetWindowsHookEx总是返回0,最后一个错误是

1428 (ERROR_HOOK_NEEDS_HMOD) Cannot set nonlocal hook without a module handle. 1428(ERROR_HOOK_NEEDS_HMOD)如果没有模块句柄,则无法设置非本地挂钩。

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. 谢谢。

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." 有关钩子的MSDN文档说:“如果应用程序为其他应用程序的线程安装了钩子过程,则该过程必须在DLL中。”

This is because your DLL is loaded into the address-space of the other application; 这是因为您的DLL已加载到另一个应用程序的地址空间中。 you then need to find some mechanism (eg 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. 但是,与大多数文档( 在此处提到)相反,键盘和鼠标挂钩无需DLL就可以工作。 That's why they worked for you. 这就是为什么他们为您工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM