错误:向非托管代码传递委托时,托管应用程序必须让这些委托保持活动状态,直到确信不会再次调用它们

错误:

对“wpfMouse!wpfMouse.MainWindow+LowLevelMouseProc::Invoke”类型的已垃圾回收委托进行了回调。

这可能会导致应用程序崩溃、损坏和数据丢失。向非托管代码传递委托时,托管应用程序必须让这些委托保持活动状态,直到确信不会再次调用它们。

代码:

private IntPtr SetHook(LowLevelMouseProc proc)
       {
           using (Process curProcess = Process.GetCurrentProcess())
           using (ProcessModule curModule = curProcess.MainModule)
           {
                return SetWindowsHookEx(WH_MOUSE_LL, HookCallback,
                   GetModuleHandle(curModule.ModuleName), 0);
           }
       }

 

private  IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
       {

           if (nCode >= 0 && MouseMessages.WM_MOUSEMOVE == (MouseMessages)wParam)
           {
               hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                System.Diagnostics.Debug.WriteLine(hookStruct.pt.x + ", " + hookStruct.pt.y);

           }

           return CallNextHookEx(_hookID, nCode, wParam, lParam);
       }

开始找MSDN, http://msdn.microsoft.com/zh-cn/library/4ca6d5z7(VS.80).aspx 

加了一个方法

Marshal.FreeCoTaskMem(lParam); 症状还是有.

 

在我们神奇的博客园上找答案.

发现两位大侠的文章

http://www.cnblogs.com/eashion/archive/2008/12/23/1360673.html

http://www.cnblogs.com/joe62/archive/2009/12/18/1626900.html

 

正确解决是,用代理. 不直接调用回调函数

 

private LowLevelMouseProc _proc;
private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);

private IntPtr SetHook(LowLevelMouseProc proc)
       {
           using (Process curProcess = Process.GetCurrentProcess())
           using (ProcessModule curModule = curProcess.MainModule)
           {

                _proc=HookCallback;
                return SetWindowsHookEx(WH_MOUSE_LL, proc,
                   GetModuleHandle(curModule.ModuleName), 0);
           }
       }

posted @ 2010-12-10 16:06  rourke  阅读(2651)  评论(0编辑  收藏  举报