【问题标题】:SetWindowsHookEx returns with "Invalid window handle" since moving to .net 4.0自从移至 .net 4.0 后,SetWindowsHookEx 返回“无效的窗口句柄”
【发布时间】:2011-04-19 19:09:04
【问题描述】:

由于从2.0 移动到.net 4.0,我无法成功运行SetWindowsHookEx 函数。它总是以Win32 错误号1400: "Invalid window handle" 结尾。

这是 pinvoke 签名:

[DllImport("user32.dll", SetLastError = true, EntryPoint = "SetWindowsHookExA", CharSet = CharSet.Ansi)]
public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProcDelegate lpfn, int hModule, int dwThreadId);

这是电话:

SetWindowsHookEx(WH_KEYBOARD_LL, HookProc, iModule, 0);

它以前工作过。为什么它会返回一个“无效的窗口句柄”错误呢?

顺便说一句:在 Windows 7 上它可以工作,但只有当我设置 iModule = 0 时。在 XP 上它无论如何都不起作用。

【问题讨论】:

    标签: .net-4.0 c#-4.0 pinvoke


    【解决方案1】:

    问题已解决:

    问题在于 iModule。我是这样分配的:

    int iModule = System.Runtime.InteropServices.Marshal.GetHINSTANCE(
        System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0])
    ).ToInt32();
    

    而正确的做法显然是:

    int iModule = System.Diagnostics.Process.GetCurrentProcess().MainModule.BaseAddress.ToInt32();
    

    但我很高兴知道其中的原因。从逻辑上讲,GetModules()[0] 将 dll 文件本身提供给回调函数所在的位置,而 GetCurrentProcess().MainModule.BaseAddress 返回主模块(dll 文件?),这可能与保存回调函数的 dll 不同.

    那么根据我的理解,为什么它实际上是“反过来”工作的?在我更改 .net 版本之前它是如何工作的?

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      相关资源
      最近更新 更多