c# - PInvoke 调用外部 SetWindowsHookEx 和 GetModuleHandle 时出错

标签 c# hook pinvoke setwindowshookex

我正在尝试将程序中的 Windows Hook 设置为外部 EXE。这将用于监 window 口的大小调整/最小化,因此我可以类似地调整程序大小,停靠到窗口。

如何解决下面的错误代码 1428126

当使用 null hMod 调用 SetWindowsHookEx 时,我收到此错误 1428。如果传递当前模块(而不是 IntPtr.Zero),我会得到相同的错误,这似乎是正确的,如下所示:

IntPtr module = PInvoke.GetModuleHandle(null);
[...]
SetWindowsHookEx(...,...,module,...);
int error = PInvoke.GetLastError();

1428 = 在没有模块句柄的情况下无法设置非本地钩子(Hook)

我还尝试使用GetModuleHandle来获取我作为模块 Hook 的外部程序:

IntPtr module = PInvoke.GetModuleHandle("communicator.exe");
int error = PInvoke.GetLastError();

但是错误随后设置为:

126 = 找不到指定的模块。

我正在使用以下 PInvoke 语句:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetWindowsHookEx(HookType hookType, HookProc lpfn, IntPtr hMod, uint dwThreadId);

这是出现问题的过程:

public void Install(IntPtr hWnd)
    {
        uint threadId;
        uint processId;

        if (hWnd == IntPtr.Zero)
        {
            threadId = (uint)AppDomain.GetCurrentThreadId();
            throw new Exception("Lync thread not found!");
        }
        else
        {
            threadId = PInvoke.GetWindowThreadProcessId(hWnd, out processId);
        }

        //IntPtr module = PInvoke.GetModuleHandle(null);
        //IntPtr module = PInvoke.GetModuleHandle(GetType().Module.FullyQualifiedName);
        IntPtr module = PInvoke.GetModuleHandle("communicator.exe");
        int error = PInvoke.GetLastError();

        m_hhook = PInvoke.SetWindowsHookEx(
            m_hookType,
            m_filterFunc,
            //Process.GetCurrentProcess().Handle,
            //threadId);
            //IntPtr.Zero,
            //module,
            //Marshal.GetHINSTANCE(
            //                                System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]
            //                        ).ToInt32()
            module,
            threadId);

        //IntPtr hinst = Marshal.GetHINSTANCE(Process.GetCurrentProcess().Handle);

        // http://msdn.microsoft.com/en-us/library/ms681385
        // ERROR_HOOK_NEEDS_HMOD - 1428 = Cannot set nonlocal hook without a module handle
        error = PInvoke.GetLastError();
    }

最佳答案

您不能使用GetModuleHandle对于外部进程。它必须是已加载到当前进程中的模块。

关于c# - PInvoke 调用外部 SetWindowsHookEx 和 GetModuleHandle 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7774509/

相关文章:

c# - GraphicsPath.AddString() 中具有某些字体和字符的通用 GDI+ 异常

c# - 文件未找到异常 : Could not load file or assembly

C# Dll导入麻烦

c# - 在 C# 中解析相对日期(如谷歌日历可以)的库

c# - 从 RowDataBound 事件的 gridview 的单元格中获取值

git - 我可以将 git hook 文件添加到存储库中,以便每个人都拥有它们吗

C++ 从远程控制台应用程序检索内容

c++ - 如何使用 asm Hook C++ 函数

c# - 如何在 C# 的 delphi dll 中调用此函数

c# - 将结构列表从 C# 应用程序传递到 C++ DLL