samedi 6 décembre 2014

Detecting specific key in low level keyboard hook


Vote count:

0




I'm creating an application that places an icon on the system tray that changes its appearance beased on the state of the Caps Lock key. The issue I'm facing is that the hook only works correctly after a key other than Caps Lock is pressed, since that key flips the check after the hook is passed through, making the icon display the wrong state incorrectly.


I would need a way to detect when the Caps Lock key is pressed inside the hook to flip the detected state.



private static NotifyIcon notifyIcon = new NotifyIcon();
private static bool CapsPressed = Control.IsKeyLocked(Keys.CapsLock);
static Icon
AppIcon = CapsIndicator.Properties.Resources.AppIcon,
OnIcon = CapsIndicator.Properties.Resources.OnIcon,
OffIcon = CapsIndicator.Properties.Resources.OffIcon;

static void UpdateIcon() {
notifyIcon.Icon = CapsPressed ? OnIcon : OffIcon;
}

// Hook initializing & other stuff here

private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
if (nCode >= 0 && wParam == (IntPtr) WM_KEYDOWN) {
CapsPressed = Control.IsKeyLocked(Keys.CapsLock);
UpdateIcon();
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}


asked 19 secs ago

DJDavid98

2,479

1 Answer



Vote count:

0




The solution isn't very straight-forward, but the key code can be extracted from the lParam argument. You can do this by converting it to a 32-bit integer using Marshal.ReadInt32 then comparing that with Keys.CapsLock (or any other key) after a cast to Keys:



private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
if (nCode >= 0 && wParam == (IntPtr) WM_KEYDOWN) {
int vkCode = Marshal.ReadInt32(lParam);

CapsPressed = Control.IsKeyLocked(Keys.CapsLock);
// Flip the detected value if CapsLock is pressed
if ((Keys) vkCode == Keys.CapsLock) CapsPressed = !CapsPressed;

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


answered 19 secs ago

DJDavid98

2,479





Detecting specific key in low level keyboard hook

Aucun commentaire:

Enregistrer un commentaire