托管调试助手“CallbackOnCollectedDelegate”在“D:\XXX\XXX.vshost.exe”中检测到问题。
其他信息: 对“XXX+HookProc::Invoke”类型的已垃圾回收委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。向非托管代码传递委托时,托管应用程序必须让这些委托保持活动状态,直到确信不会再次调用它们。
经过搜索资料,发现出问题的原因是我的程序里回调函数作用域的问题 (_mouseHookCallBack)
报错前代码:
private void Ok_Click(object sender, EventArgs e)
{
HookProc _mouseHookCallBack; // 声明鼠标钩子事件类型 // 安装鼠标钩子
if (_hMouseHook == IntPtr.Zero)
{
// 生成一个HookProc的实例.
_mouseHookCallBack = new HookProc(MouseHookProc); var mar = LoadLibraryW("user32.dll"); _hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, _mouseHookCallBack, mar, );
}
} IntPtr _hMouseHook = IntPtr.Zero; // 鼠标钩子句柄 private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
...
}
修改后代码:
private void Ok_Click(object sender, EventArgs e)
{
// 安装鼠标钩子
if (_hMouseHook == IntPtr.Zero)
{
// 生成一个HookProc的实例.
_mouseHookCallBack = new HookProc(MouseHookProc); var mar = LoadLibraryW("user32.dll"); _hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, _mouseHookCallBack, mar, );
}
} HookProc _mouseHookCallBack; // 声明鼠标钩子事件类型 IntPtr _hMouseHook = IntPtr.Zero; // 鼠标钩子句柄 private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
...
}
参考