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;
}
}
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);
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); }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With