Skip to content

Commit ecc480f

Browse files
committed
Update KeyboardHook.cs
Resolve the issue of weak hook expiration and modify it to 3 hours for re registration
1 parent 6631e6f commit ecc480f

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed

Nimble/Helpers/KeyboardHook.cs

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22
using System.Reflection;
33
using System.Runtime.InteropServices;
44
using System.Windows.Input;
5+
using System.Windows.Threading;
56

67
namespace Nimble.Helpers
78
{
89
public partial class KeyboardHook
910
{
11+
private DispatcherTimer _dispatcherTimer;
12+
1013
#region pinvoke details
1114

1215
private enum HookType : int
@@ -64,6 +67,27 @@ public KeyboardHook()
6467
{
6568
_hookFunction = new HookProc(HookCallback);
6669
Install();
70+
var osVersion = Environment.OSVersion.Version;
71+
if (osVersion.Major > 6 || (osVersion.Major == 6 && osVersion.Minor >= 2))
72+
{
73+
_dispatcherTimer = new DispatcherTimer();
74+
_dispatcherTimer.Tick += _dispatcherTimer_Tick;
75+
_dispatcherTimer.Interval = new TimeSpan(3, 0, 0);
76+
_dispatcherTimer.Start();
77+
}
78+
}
79+
80+
void CreateKeyHook()
81+
{
82+
Uninstall();
83+
Install();
84+
}
85+
86+
private void _dispatcherTimer_Tick(object sender, EventArgs e)
87+
{
88+
_dispatcherTimer.Stop();
89+
CreateKeyHook();
90+
_dispatcherTimer.Start();
6791
}
6892

6993
~KeyboardHook()
@@ -76,11 +100,11 @@ private int HookCallback(int code, IntPtr wParam, ref KBDLLHOOKSTRUCT lParam)
76100
if (code < 0)
77101
return CallNextHookEx(_hookHandle, code, wParam, ref lParam);
78102

79-
if ((lParam.flags & 0x80) != 0 && this.KeyUp != null)
80-
this.KeyUp(this, new HookEventArgs(lParam.vkCode));
103+
if ((lParam.flags & 0x80) != 0 && KeyUp != null)
104+
KeyUp(this, new HookEventArgs(lParam.vkCode));
81105

82-
if ((lParam.flags & 0x80) == 0 && this.KeyDown != null)
83-
this.KeyDown(this, new HookEventArgs(lParam.vkCode));
106+
if ((lParam.flags & 0x80) == 0 && KeyDown != null)
107+
KeyDown(this, new HookEventArgs(lParam.vkCode));
84108

85109
return CallNextHookEx(_hookHandle, code, wParam, ref lParam);
86110
}
@@ -90,7 +114,7 @@ private void Install()
90114
if (_hookHandle != IntPtr.Zero)
91115
return;
92116

93-
Module[] list = System.Reflection.Assembly.GetExecutingAssembly().GetModules();
117+
Module[] list = Assembly.GetExecutingAssembly().GetModules();
94118
System.Diagnostics.Debug.Assert(list != null && list.Length > 0);
95119

96120
_hookHandle = SetWindowsHookEx(_hookType,
@@ -114,7 +138,7 @@ public class HookEventArgs : EventArgs
114138

115139
public HookEventArgs(UInt32 keyCode)
116140
{
117-
this.Key = System.Windows.Input.KeyInterop.KeyFromVirtualKey((int)keyCode);
141+
Key = KeyInterop.KeyFromVirtualKey((int)keyCode);
118142
}
119143
}
120144

0 commit comments

Comments
 (0)