C# SetWindowsHookEx不';不能使用线程Id

C# SetWindowsHookEx不';不能使用线程Id,c#,c++,setwindowshookex,C#,C++,Setwindowshookex,大家好,提前向所有愿意帮助的人表示感谢。 我正在尝试设置一个CBT windows钩子,当我全局设置它时,它工作得很好,但每当我尝试将它附加到单个线程时,它就会失败。据我所知,我做每件事都有章可循: -我从非托管dll中公开了钩子过程 -我的应用程序、dll和线程进程都是32位的 -我使用的线程ID是正确的(用spy++确认) 当我试图从一个C++代码中只勾出一个线程时,我设法做到了…您能否仅从非托管代码钩住单个线程 下面是我的代码: [DllImport( "user32.dll", SetL

大家好,提前向所有愿意帮助的人表示感谢。 我正在尝试设置一个CBT windows钩子,当我全局设置它时,它工作得很好,但每当我尝试将它附加到单个线程时,它就会失败。据我所知,我做每件事都有章可循: -我从非托管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
    }
这一声明是错误的。最后一个参数(dwThreadId)的类型是DWORD,它是C#中的一个uint


奇怪的是,你没有收到关于这一点的Pinvokestack警告。这表明您正在64位操作系统上运行。如果添加了几个额外的故障模式,则插入的DLL必须包含编译为进程和要挂接的进程的正确位的非托管代码。根据需要设置项目的平台目标。您的代码缺少所有错误检查,因此您不知道它为什么不起作用,请确保在收到失败返回代码时抛出新的Win32Exception()。

Marshal.GetLastWin32Error有什么要说的?起初它是uint而不是ulong,它也不适用于uint。没有记录winapi函数失败和未设置GetLastError()返回值的案例。没有代码可供查看,也没有方法测试,我几乎无法帮助您克服这一障碍。
[DllImport( "user32.dll", SetLastError = true )]
static extern IntPtr SetWindowsHookEx ( int hookType, UIntPtr lpfn, 
                                        IntPtr hMod, ulong dwThreadId );