SetWindowsHookEx doesn't work with thread Id
Hello and thanks in advance to anyone thatll try to help. I'm trying to set a CBT windows hook, which works well when Im setting it globally, but fails whenever I try to attach it to a single thread. As far as I know, Im doing everything by the book: - I exposed the hook procedure from an unmanaged dll - my application, the dll and the thread's process are all 32 bit - The thread ID I use is correct (confirmed with spy++)
When I tried to hook only one thread from a c++ code, I managed to do it... can you hook a single thread only from unmanaged code?
here is my code anyway:
[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 bo开发者_如何学Goth 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 );
That declaration is wrong. The type of the last argument (dwThreadId) is DWORD, an uint in C#.
Odd that you didn't get a PInvokeStackImbalance debugger warning about that. This suggests that you are running on a 64-bit operating system. Which adds several additional failure modes, the DLL you inject must contain unmanaged code compiled to the correct bitness of both your process and the process you want to hook. Set the Platform target of your project as necessary. Your code is missing all error checking so you won't know why it doesn't work, be sure to throw new Win32Exception() when you get a failure return code.
精彩评论