public static void LockToggleKey(ToggleVirtualKeyCode value) { if (!IsToggleKeyLocked(value)) { PressReleaseToggleKey(value); } }
static void Main(string[] args) { ToggleVirtualKeyCode[] toggleVirtualKeyCodes = new ToggleVirtualKeyCode[] { ToggleVirtualKeyCode.Capital, ToggleVirtualKeyCode.Insert, ToggleVirtualKeyCode.NumLock, ToggleVirtualKeyCode.Scroll }; foreach (ToggleVirtualKeyCode toggleVirtualKeyCode in toggleVirtualKeyCodes) { Keyboard.UnlockToggleKey(toggleVirtualKeyCode); } }
/// <summary> /// From System.Windows.Forms.Control.IsKeyLocked, with ToggleVirtualKeyCode subset of VirtualKeyCode /// </summary> /// <param name="value">VirtualKeyCode that can have a toggle.</param> /// <returns>If toggle key was locked.</returns> public static bool IsToggleKeyLocked(ToggleVirtualKeyCode value) { // Detecting this with GetAsyncKeyState fails, though The Old New Thing indicates it should: http://blogs.msdn.com/b/oldnewthing/archive/2004/11/30/272262.aspx //short asyncKeyState = User32Dll.GetAsyncKeyState((int)value); short keyState = User32Dll.GetKeyState((int)value); if ((value != ToggleVirtualKeyCode.Insert) && (value != ToggleVirtualKeyCode.Capital)) { return((keyState & 0x8001) != 0); // Insert, Captial have both bits set } return((keyState & 1) != 0); // Scroll, NumLock have only lower bit set }
public static void PressReleaseToggleKey(ToggleVirtualKeyCode value) { VirtualKeyCode virtualKeyCode = (VirtualKeyCode)value; // we can do this safely: VirtualKeyCode is a superset of ToggleVirtualKeyCode pressReleaseKey(virtualKeyCode); }