且构网

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

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

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

您正在创建的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.

要的是,你需要不断给委托的引用活着,只要挂钩到位prevent(直到你调用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).