简体   繁体   English

Windows应用商店应用C#-Capslock开/关

[英]Windows store apps c# - capslock on/off

I have managed to determine if capslock is on or off, so that I can display proper error message. 我已经设法确定capslock是打开还是关闭,以便可以显示正确的错误消息。 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;
    }
}

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). 查找当前键状态的WinRT方法是GetKeyState ,因此可以根据需要直接检查键值(类似于IsKeyLocked提到的IsKeyLocked )。

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). 我会注意到,打开按下的键的哈希码似乎是错误的,您应该对照VirtualKey枚举中的代码检查键值本身(我想您已经注意到哈希码就是这个值,这意味着它可以正常工作)。

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: 通常,按键将被诸如处理它们的文本框之类的控件所消耗,但是您可以使用带有true参数的AddHandler来监听所有按键,包括已处理的按键,例如:

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

Or alternatively use the Window.Current.CoreWindow.KeyUp event. 或者,也可以使用Window.Current.CoreWindow.KeyUp事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM