託管調試助手「CallbackOnCollectedDelegate」在「D:\XXX\XXX.vshost.exe」中檢測到問題。html
其餘信息: 對「XXX+HookProc::Invoke」類型的已垃圾回收委託進行了回調。這可能會致使應用程序崩潰、損壞和數據丟失。向非託管代碼傳遞委託時,託管應用程序必須讓這些委託保持活動狀態,直到確信不會再次調用它們。函數
通過搜索資料,發現出問題的緣由是個人程序裏回調函數做用域的問題 (_mouseHookCallBack)ui
報錯前代碼:spa
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, 0); } } IntPtr _hMouseHook = IntPtr.Zero; // 鼠標鉤子句柄 private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam) { ... }
修改後代碼:.net
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, 0); } } HookProc _mouseHookCallBack; // 聲明鼠標鉤子事件類型 IntPtr _hMouseHook = IntPtr.Zero; // 鼠標鉤子句柄 private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam) { ... }
參考unix