SetWindowsHookEx 不适用于线程 ID

SetWindowsHookEx doesn't work with thread Id

本文关键字:ID 线程 适用于 不适用 SetWindowsHookEx      更新时间:2023-10-16

大家好,提前感谢任何想要帮助的人。我试图设置一个CBT窗口钩子,当我在全局设置它时效果很好,但每当我试图将它附加到单个线程时就会失败。据我所知,我做的一切都是照章办事。-我从非托管dll中暴露了钩子子程-我的应用程序,DLL和线程的进程都是32位的-我使用的线程ID是正确的(与spy++确认)

当我试图从c++代码中只钩一个线程时,我设法做到了…你能否只从非托管代码中钩住一个线程?

这是我的代码:

[DllImport( "user32.dll", SetLastError = true )]
    static extern IntPtr SetWindowsHookEx ( int hookType, UIntPtr lpfn, IntPtr hMod, uint dwThreadId );
[DllImport( "kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true )]
    public static extern UIntPtr GetProcAddress ( IntPtr hModule, string procName );
[DllImport( "kernel32", SetLastError = true, CharSet = CharSet.Unicode )]
    public static extern IntPtr LoadLibrary ( string libraryName );
const int WH_CBT = 5;
    void SetHook ()
    {
        IntPtr dll = LoadLibrary( LIBRARY );
        UIntPtr proc = GetProcAddress( dll, PROC );
        uint threadId = GetAppWindowThreadId();
         //assume that the threadId of the external window is correct, as I said I verified with spy++
         //and assume that dll and proc both get correct values
        IntPtr hookAddress = SetWindowsHookEx( WH_CBT , proc, dll, threadId );
         //hookAddress is 0
    }
[DllImport( "user32.dll", SetLastError = true )]
static extern IntPtr SetWindowsHookEx ( int hookType, UIntPtr lpfn, 
                                        IntPtr hMod, ulong dwThreadId );

这个声明是错误的。最后一个参数(dwThreadId)的类型是DWORD, c#中的一个int。

奇怪的是你没有得到pinvokestack失衡调试器警告。这表明您正在运行64位操作系统。这增加了几个额外的故障模式,您注入的DLL必须包含编译到您的进程和您想要挂钩的进程的正确位的非托管代码。根据需要设置项目的平台目标。你的代码缺少所有的错误检查,所以你不知道为什么它不工作,一定要抛出新的Win32Exception()当你得到一个失败的返回代码。