Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect NumLock on/off status in WPF

Tags:

c#

wpf

When my application is opened, initially it can detect whether the numlock is on or off, but after I on or off the numlock when the application is still opened, the numlock status still remain same as the initial one. Here's my code:

bool isNumLockedPressed = System.Windows.Input.Keyboard.IsKeyToggled(System.Windows.Input.Key.NumLock);


public MainWindow()
{
            if (isNumLockedPressed == true)                
                NumLock.Foreground = System.Windows.Media.Brushes.White;

            else
                NumLock.Foreground = System.Windows.Media.Brushes.Red;     
}

I want the numlock status follow with my on/off action. Any suggestions?

UPDATED

This is my modification so far, but still can't get what I want. Any suggestions?

bool isNumLockedPressed = System.Windows.Input.Keyboard.IsKeyToggled(System.Windows.Input.Key.NumLock);

int numLockStatus { get; set; }

public MainWindow()
{
            if (isNumLockedPressed == true)
            {
                numLockStatus = 1;
                NumLock.Foreground = System.Windows.Media.Brushes.White;
            }

            else
            {
                numLockStatus = 0;
                NumLock.Foreground = System.Windows.Media.Brushes.Red;
            }

}   

 private void NumLockKey_Press(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.NumLock)
        {
            numLockStatus = 1;
            NumLock.Foreground = System.Windows.Media.Brushes.White;
        }

        else
        {
            numLockStatus = 0;
            NumLock.Foreground = System.Windows.Media.Brushes.Red;
        }
    }
like image 597
YWah Avatar asked Oct 15 '25 20:10

YWah


2 Answers

You are calling a function and storing the result in isNumLockedPressed. The value of isNumLockedPressed will never change unless you have code that is explicitly changing it. If you want to update it with the latest value later in your code, simply repeat the function call before you check the value isNumLockedPressed = System.Windows.Input.Keyboard.IsKeyToggled(System.Windows.Input.Key.NumLock);

like image 137
Robert Levy Avatar answered Oct 17 '25 11:10

Robert Levy


So a bool is a value type, not a reference type. When you assign the value of IsKeyToggled to a value type, you are getting the value at that moment. If the value subsequently changes your local bool variable will not know it.

What you should do instead is create a utility/helper class with a static method/property.

public class KeyboardHelper 
{
    public bool IsNumLockPressed
    {
        get { return System.Windows.Input.Keyboard.IsKeyToggled(System.Windows.Input.Key.NumLock); }
    }
}
like image 34
Richthofen Avatar answered Oct 17 '25 11:10

Richthofen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!