Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind to Caps Lock

Tags:

c#

wpf

I'm building a login screen in WPF. I'm trying to figure out how to bind a part of my code to only be visible when the caps lock key is on.

<StackPanel Grid.Row="3" Grid.ColumnSpan="2" Grid.Column="1" Orientation="Horizontal">
        <Image Source="../../../Resources/Icons/109_AllAnnotations_Warning_16x16_72.png" Height="16" Width="16"/>
        <Label>Caps lock is on</Label>
</StackPanel>

I would prefer a solution with xaml binding only.

like image 400
gulbaek Avatar asked Dec 27 '22 15:12

gulbaek


1 Answers

We're using the following approach in our sign in form to show a 'Caps lock warning' when the password box has focus.

    private void PasswordBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        UpdateCapsLockWarning(e.KeyboardDevice);
    }

    private void PasswordBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        UpdateCapsLockWarning(e.KeyboardDevice);
    }

    private void PasswordBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        CapsLockWarning.Visibility = Visibility.Hidden;
    }

    private void UpdateCapsLockWarning(KeyboardDevice keyboard)
    {
        CapsLockWarning.Visibility = keyboard.IsKeyToggled(Key.CapsLock) ? Visibility.Visible : Visibility.Hidden;
    }

Not the binding-only answer you're looking for though.

like image 59
Mårten Wikström Avatar answered Jan 09 '23 15:01

Mårten Wikström