Search code examples
c#keyboardoverridingcapslock

How to call a keyboard key press programmatically?


Problem: Calling a keyboard key to be pressed, from a piece of C# code but here's the catch: the key-press should not be limited to the process/application but received by the entire operating system, so also when the program is in the background and a different form/program has focus

Goal: make a program that locks the state of CapsLock and NumLock

Background: I have a laptop, and these 2 keys frustrate me to much, I want to make a application that runs in the background, and that disables CapsLock as soon as it gets accidentally enabled, and for NumLock to never be disabled, also, I want to extend my knowledge about coding, I have tried to find solutions, but none of them solve the (entire) problem.


Solution

  • using System;
    using System.Runtime.InteropServices;
    
    public class CapsLockControl
    {
    
        public const byte VK_NUMLOCK = 0x90;
        public const byte VK_CAPSLOCK = 0x14;
    
        [DllImport("user32.dll")]
            static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,UIntPtr dwExtraInfo);
        const int KEYEVENTF_EXTENDEDKEY = 0x1;
        const int KEYEVENTF_KEYUP = 0x2;
    
        public static void Main()
        {
            if (Control.IsKeyLocked(Keys.CapsLock))
            {
                Console.WriteLine("Caps Lock key is ON.  We'll turn it off");
                keybd_event(CapsLockControl.VK_CAPSLOCK, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr) 0);
                keybd_event(CapsLockControl.VK_CAPSLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                    (UIntPtr) 0);
            }
            else
            {
                Console.WriteLine("Caps Lock key is OFF");
            }
        }
    }