Вопрос

I have a simple Windows Store / Modern UI app which has a RichEditBox. I'm trying to handle CTRL+B / CTRL+I etc to set bold / italic text on and off but I'm encountering some weird behaviour. Here's my code:

private void RichEditBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
    var state = Window.Current.CoreWindow.GetKeyState(Windows.System.VirtualKey.Control);
    if (state == CoreVirtualKeyStates.Down)
    {
        console.Text += "^";
    }
    else
    {
        console.Text += ".";
    }
}

console is just a TextBlock above the RichEditBox control

If I press CTRL ten times, I would expect the output to be

^^^^^^^^^^

However, what I get is this

.^.^.^.^.^

CTRL only registers every second time. What's happening?

Это было полезно?

Решение

Beware of an enum type that have the [Flags] attribute, values of the enum type can have multiple flags turned on. Certainly the case here, you'll also get the Locked flag turned on for modifier keys. Quirky since the Ctrl key isn't actually a locked key, it is still synthesized by Windows though.

For enum types that have [Flags] you need to isolate the flag you are interested in, like this:

    if ((state & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down) {
        console.Text += "^";
    }

Which fixes your problem.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top