SetWindowsHookEx 不适用于线程 ID
SetWindowsHookEx doesn't work with thread Id
大家好,提前感谢任何想要帮助的人。我试图设置一个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()当你得到一个失败的返回代码。
相关文章:
- 我应该在C++中打印线程 ID 吗?
- 我可以使用Qt线程ID为每个线程创建唯一的缓存吗?
- 这种基于线程 ID 的同步是否安全整洁?
- OpenMP:当我按线程 ID 访问共享变量时,我是否需要一个关键部分
- C 不同的线程在FreeBSD 10上具有相同的线程ID
- 如何获取正确的线程 ID 和值
- 调试器看到的输出线程 ID
- 如何从父线程中提取 pthread 的任务 id(tid)
- 是否可以向特定的线程 ID 发送信号?
- 与上一个线程具有相同ID的线程同步
- C++ 中 OpenMP 中的有序线程 ID
- 如何通过id获取线程对象?
- 您可以在 OpenMP 中将特定线程 ID 分组到唯一的任务组中吗?
- 查找称为函数C 的线程ID
- 确定进程的输入线程 ID
- C++ 中"main"线程的 ID
- SetWindowShookex(WH_KEYBOARD)无法与线程ID一起使用
- 在性能方面获取线程 ID 是否昂贵
- 标准::线程::id的要求.可以雾化吗?
- 如何知道谁是给定线程 ID 的父线程