In C# en VB.NET kan je via Console.CapsLock controleren of de Caps-lock toets is ingeschakeld. Idem voor Console.NumberLock. Vreemd genoeg niet voor Scroll-lock. In VB.NET heb je ook de My.Computer.Keyboard klasse, waar wel de status van Scroll-lock kan worden opgevraagd.
In de Win32 API beschikken we ook over de functie SetKeyboardState(). Maar deze functie is niet te gebruiken om de Caps-lock, Scroll-lock en Num-lock toetsen in- of uit te schakelen. Hoe dat wel kan staat in dit codeknipsel.
De volgende code laat een speelse manier zien waarop deze klasse gebruikt kan worden:
ToggleKeys t = new ToggleKeys();
for (int i = 0; i < 50; i++)
{
t.ToggleNumLock();
System.Threading.Thread.Sleep(200);
t.ToggleCapsLock();
System.Threading.Thread.Sleep(200);
t.ToggleScrollLock();
System.Threading.Thread.Sleep(200);
}
Veel plezier ermee!
using System; using System.Runtime.InteropServices; public class ToggleKeys { // API declarations: [DllImport("user32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)] private static extern void keybd_event(byte bVk, byte bScan, long dwFlags, long dwExtraInfo); [DllImport("user32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)] private static extern long GetKeyboardState(byte pbKeyState); [DllImport("user32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)] private static extern long SetKeyboardState(byte lppbKeyState); // Constant declarations: const int VK_NUMLOCK = 0x90; const int VK_SCROLL = 0x91; const int VK_CAPITAL = 0x14; const int KEYEVENTF_EXTENDEDKEY = 0x1; const int KEYEVENTF_KEYUP = 0x2; private bool NumLockState; private bool ScrollLockState; private bool CapsLockState; private byte[] keys = new byte[256]; public void ToggleNumLock() { GetKeyboardState(keys[0]); // NumLock handling: NumLockState = Convert.ToBoolean(keys[VK_NUMLOCK]); if (NumLockState != true) //Turn numlock on { //Simulate Key Press keybd_event(VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0); //Simulate Key Release keybd_event(VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); } } public void ToggleCapsLock() { GetKeyboardState(keys[0]); // CapsLock handling: CapsLockState = Convert.ToBoolean(keys[VK_CAPITAL]); if (CapsLockState != true) //Turn capslock on { //Simulate Key Press keybd_event(VK_CAPITAL, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0); //Simulate Key Release keybd_event(VK_CAPITAL, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); } } public void ToggleScrollLock() { GetKeyboardState(keys[0]); // ScrollLock handling: ScrollLockState = Convert.ToBoolean(keys[VK_SCROLL]); if (ScrollLockState != true) //Turn Scroll lock on { //Simulate Key Press keybd_event(VK_SCROLL, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0); //Simulate Key Release keybd_event(VK_SCROLL, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); } } }comments powered by Disqus