Getting Key States at Any Time

If the KeyDown, KeyUp, and AcceleratorKeyActivated events were all you had to work with, detecting key combinations (such as Alt+G) would be awkward. Each key is reported one-at-a-time, so you would need a member variable representing the state of Ctrl to set on KeyDown and clear on KeyUp. Then you could check its value when receiving another event for the letter G.

Fortunately, there are two methods for determining the state of any key at any time: GetKeyState and GetAsyncKeyState. These methods are tucked away in Window.Current.CoreWindow, a surprisingly obscure place for an important feature. This is not just useful for key combinations, but for code that isn’t driven by input events, such as a game loop.

With ...

Get Universal Windows® Apps with XAML and C# Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.