且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 WPF/C# 中使用全局键盘钩子 (WH_KEYBOARD_LL)

更新时间:2021-09-26 08:00:04

您正在 SetHook 方法调用中创建内联回调委托.该委托最终将被垃圾收集,因为您没有在任何地方保留对它的引用.一旦委托被垃圾回收,您将不会再收到任何回调.

You're creating your callback delegate inline in the SetHook method call. That delegate will eventually get garbage collected, since you're not keeping a reference to it anywhere. And once the delegate is garbage collected, you will not get any more callbacks.

为了防止这种情况发生,只要挂钩就位(直到您调用 UnhookWindowsHookEx),您就需要保持对委托的引用处于活动状态.

To prevent that, you need to keep a reference to the delegate alive as long as the hook is in place (until you call UnhookWindowsHookEx).