Question

I have managed to determine if capslock is on or off, so that I can display proper error message. But my code works only, if capslock is off when textbox gets focus. But if it is on, then error message appears when it shouldn't.

private Boolean CapsLock = false; //here...how to determine if it is on or off propperly
private void loginCredentials_KeyUp(object sender, KeyRoutedEventArgs e)
{ 
    switch (e.Key.GetHashCode())
    {
        //...
        case 20: 
            CapsLock = (CapsLock) ? false : true;
            errorMessage.Text = (CapsLock) ? ((App)(App.Current)).loader.GetString("capslockError") : String.Empty;
            break;
    }
}
Was it helpful?

Solution

The WinRT method to find the current key status is GetKeyState, so you can check the key value directly if you need to (similar to the IsKeyLocked mentioned in comments).

I'd note that switching on the hashcode of the key pressed seems wrong, you should check the key value itself against the code from the VirtualKey enum (I guess you've noticed that the hash code is just this value, meaning that it works).

If you do need to know immediately when a key such as the caps lock is pressed in general, not just when your text field has focus, you can register a key handler on the application root visual. Normally key presses will be consumed by controls like a text box that handle them, but you can use AddHandler with true parameter to listen to all key presses including handled ones, something like:

Window.Current.AddHandler(UIElement.KeyUpEvent, new KeyEventHandler(...), true);

Or alternatively use the Window.Current.CoreWindow.KeyUp event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top