【发布时间】:2011-08-28 11:04:04
【问题描述】:
您好,提前感谢任何愿意提供帮助的人。 我正在尝试设置一个 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
}
【问题讨论】:
-
Marshal.GetLastWin32Error 有什么要说的?
标签: c# c++ setwindowshookex