Question

In my c# windows store app I have the following line of code to detect if the CTRL key is pressed. I got this code from an online sample, and it works perfectly.

var state = Window.Current.CoreWindow.GetKeyState(Windows.System.VirtualKey.Control);
if ((state & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down)
{
    // do something with e.Key
}

Specifically, I've never seen the syntax in the if statement before.

+ is for adding ints or concatenating strings, and && is for combining 2 boolean expressions, so what does & do in this context?

Was it helpful?

Solution

It's a bitwise AND, and checks whether that certain bit (or bits have been set).

You might want to Google for the FlagsAttribute on enums. They explain what you want to understand.

In this example you want to see the key state of Control.

OTHER TIPS

That's a bitwise AND operator. Your state might contain several other bit flags, but you are only interested in the "Down" flag in this case. So the & operator is filtering all of those other (possible) flags away so only this one is tested by the == operator.

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