Thread hook procedure is no longer called after pressing Tab several times. Why?

后端 未结 2 701
无人共我
无人共我 2021-01-06 08:37

I installed a thread-specific windows hook to monitor messages sent to WndProc. It worked at first. However, after I pressed Tab about 19 times to move focus around a form,

2条回答
  •  一向
    一向 (楼主)
    2021-01-06 09:01

    While testing your program I got the following error

    CallbackOnCollectedDelegate was detected
    Message: A callback was made on a garbage collected delegate of type 'Sandbox Form!Sandbox_Form.Program+HookProc::Invoke'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.

    I believe the problem is the delegate that is implicitly created to be passed in to SetWindowsHookEx for the callback is getting garbage collected. By explicitly creating a variable for the delegate and keeping it in scope I think it will make your problem go away, when I modified InstallHook to the following I could no longer re-create the error.

    private static HookProc hookProcDelegate;
    
    private static void InstallHook()
    {
        if (Program.hWndProcHook == IntPtr.Zero)
        {
            Console.WriteLine("Hooking...");
    
            hookProcDelegate = new HookProc(WndProcHookCallback);
    
            Program.hWndProcHook = SetWindowsHookEx(
                WH_CALLWNDPROC,
                hookProcDelegate,
                GetModuleHandle(null),
                GetCurrentThreadId());
    
            if (Program.hWndProcHook != IntPtr.Zero)
                Console.WriteLine("Hooked successfully.");
            else
                Console.WriteLine("Failed to hook.");
        }
    }
    

提交回复
热议问题