Turn On and Off Numlock Key using C# (.Net Framework 4.7)

163 views Asked by At

I have tried with InputSimulator and InputSimulatorPlus package also.

  • Require Condition as below

    if current_Number Odd: turn Off NumLock Key
    
    if current_Number Even : turn On NumLock Key
    
bool numLockEnabled = Control.IsKeyLocked(Keys.NumLock);
  for (int current_Number = 0; current_Number  < 10; current_Number ++)
  {
    // Toggle the NumLock key
        if (current_Number % 2 == 0)
        {
            // NumLock is currently on, turn it off
            SendKeys.SendWait("{NUMLOCK}");
       }
       else
       {
            // NumLock is currently off, turn it on
           SendKeys.SendWait("{NUMLOCK}");
      }
      System.Threading.Thread.Sleep(2000);
      Console.WriteLine($" current_Number Value {current_Number} , numLockEnabled {numLockEnabled} , Control.IsKeyLocked(Keys.NumLock)  {Control.IsKeyLocked(Keys.NumLock)}");
 }
  • Current Output
current_Number  Value  0 , numLockEnabled True , Control.IsKeyLocked(Keys.NumLock) True
current_Number  Value  1 , numLockEnabled True , Control.IsKeyLocked(Keys.NumLock) True
current_Number  Value  2 , numLockEnabled True , Control.IsKeyLocked(Keys.NumLock) True
...
current_Number  Value  9 , numLockEnabled True , Control.IsKeyLocked(Keys.NumLock) True

  • Require Output
current_Number  Value  0 , numLockEnabled True , Control.IsKeyLocked(Keys.NumLock) False
current_Number  Value  1 , numLockEnabled True , Control.IsKeyLocked(Keys.NumLock) True
...
current_Number  Value  9 , numLockEnabled True , Control.IsKeyLocked(Keys.NumLock) True
1

There are 1 answers

1
samgi On

The NumLock key is turned off when the current number is odd and turned on when the current number is even. The Control.IsKeyLocked(Keys.NumLock) method is used to check the current state of the NumLock key. The SendKeys.SendWait() method is used to send a key press and wait for the key to be released.

bool numLockEnabled = Control.IsKeyLocked(Keys.NumLock);
            for (int current_Number = 0; current_Number < 10; current_Number++)
            {
                // Toggle the NumLock key
                if (current_Number % 2 == 0)
                {
                    // NumLock is currently on, turn it off
                    bool isNumLockOn = Control.IsKeyLocked(Keys.NumLock);
                    SendKeys.SendWait(isNumLockOn ? "NUMLOCK" : "{NUMLOCK}");
                }
                else
                {
                    // NumLock is currently off, turn it on
                    bool isNumLockOn = Control.IsKeyLocked(Keys.NumLock);
                    SendKeys.SendWait(isNumLockOn ? "{NUMLOCK}" : "NUMLOCK");
                }

                Thread.Sleep(2000);
                Console.WriteLine($"current_Number Value {current_Number}, numLockEnabled {numLockEnabled}, Control.IsKeyLocked(Keys.NumLock) {Control.IsKeyLocked(Keys.NumLock)}");
            }