【发布时间】:2021-03-05 02:45:40
【问题描述】:
我正在尝试使用托管 C# 代码中的 C++ DLL 将 LOCAL 键盘挂钩安装到进程中,如下所示:
public class KeyboardHook
{
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("DLL.dll", CallingConvention = CallingConvention.Cdecl)]
protected static extern IntPtr Install(int idHook, IntPtr windowHandle, HookCallback callback);
private IntPtr instance;
private HookCallback handler;
public KeyboardHook()
{
instance = IntPtr.Zero;
handler = Callback;
}
public void Install(Process process)
{
instance = Install(WH_KEYBOARD, process.MainWindowHandle, handler);
}
public void Uninstall()
{
UnhookWindowsHookEx(instance);
}
private IntPtr Callback(int nCode, IntPtr wParam, IntPtr lParam)
{
// TODO Use hook data here
return CallNextHookEx(instance, nCode, wParam, lParam);
}
}
C++ DLL 代码应该足以将挂钩数据分派给 C# 的 Callback 函数,如下所示:
// dll.h
#pragma data_seg(".foo")
HOOKPROC _hookCallback = NULL;
#pragma comment(linker, "/SECTION:.foo,RWS")
#pragma data_seg()
static HINSTANCE _moduleHandle = NULL;
extern "C" __declspec(dllexport)
HHOOK Install(int idHook, HWND window, HOOKPROC hookCallback);
extern "C" __declspec(dllexport)
LRESULT CALLBACK HookProc(int code, WPARAM wparam, LPARAM lparam);
// dll.cpp
HHOOK Install(int idHook, HWND window, HOOKPROC hookCallback)
{
auto processId = 0ul;
auto threadId = GetWindowThreadProcessId(window, &processId);
_hookCallback = hookCallback;
_hookCallback(-1, NULL, NULL); // Test callback (works)
return SetWindowsHookExA(idHook, HookProc, _moduleHandle, threadId);
}
LRESULT CALLBACK HookProc(int code, WPARAM wParam, LPARAM lParam)
{
// The following line terminates the target process
return _hookCallback(code, wParam, lParam);
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
_moduleHandle = hModule;
break;
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
本地挂钩已成功安装,因为触发了 DLL KeyboardProc 函数,但是,从 C++ DLL 调用 C# 委托会终止应用程序。为什么?
注意事项:
- DLL 和应用程序都是 32 位的
-
当
HookProc被触发时_hookCallback_不为空(虽然我不确定它是否指向一个有效的内存地址) -
KeyboardProc::handler不应被垃圾回收,因为 KeyboardProc 实例的存在时间与 C# 应用程序一样长 - 在 DLL 的
Install函数中使用_hookCallback函数指针可以完美运行,但在HookProc函数中使用时会终止进程。 - 没有任何异常,进程突然终止
还尝试过什么:
使HookCallback 成为UnmanagedFunctionPointer,以及使用Marshal.GetFunctionPointerForDelegate 并通过使用GCHandle.Alloc() 和GC.KeepAlive() 告诉垃圾收集器不要收集handler 属性:
public class KeyboardHook
{
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("DLL32.dll", CallingConvention = CallingConvention.Cdecl)]
protected static extern IntPtr Install(int idHook, IntPtr windowHandle, IntPtr delegatePointer);
// ...
protected readonly GCHandle garbageCollectorHandle;
public KeyboardHook()
{
instance = IntPtr.Zero;
handler = new HookCallback(Callback);
garbageCollectorHandle = GCHandle.Alloc(handler); // Or GC.KeepAlive(handler)
}
~KeyboardHook()
{
garbageCollectorHandle.Free();
}
public void Install(Process process)
{
IntPtr delegatePointer = Marshal.GetFunctionPointerForDelegate(handler);
instance = Install(WH_KEYBOARD, process.MainWindowHandle, delegatePointer);
}
// ...
}
将handler直接使用到SetWindowsHookExA(C++):
HHOOK Install(int idHook, HWND window, HOOKPROC hookCallback)
{
auto processId = 0ul;
auto threadId = GetWindowThreadProcessId(window, &processId);
_hookCallback = hookCallback;
return SetWindowsHookExA(idHook, hookCallback, _moduleHandle, threadId);
}
【问题讨论】:
-
在另一个函数中添加
GC.KeepAlive(handler);,可能在Uninstall中 -
@Charlieface 你能解释一下吗?
HookProc会立即终止进程,不仅是在卸载挂钩之后。 -
见stackoverflow.com/questions/52952678/… 虽然知道确切的例外情况会有所帮助
-
这就是问题所在。我不知道会发生什么样的异常。进程突然终止。
-
如果您需要函数指针在
Install的生命周期之外 保持活动状态,那么您需要在Install之外的委托上使用KeepAlive。如果您查看 Windows 事件查看器 -> 应用程序事件,您应该在那里找到异常。我不明白为什么这根本需要另一个 C++ dll,你可以从 C# 完成整个事情。