CoreWindow.GetKeyState() returns the key status with the combination of CoreVirtualKeyStates? RRS feed

  • Question

  • Hi,

    It looks CoreWindow.GetKeyState()  return the result with the convination of CoreVirtualKeyStates.

    For example, when I keep pressing [Shift] keyboard, CoreWindow.GetKeyState() against [Shift] key returns 3.

    The API spec for GetKeyState says it returns enumeration of CoreVirtualKeyStates.


    As we can see, there is no value 3 defined here.

    From the behavior, it looks the API returns 3 as the status of Down(1) + Locked(2).

    Is this the expected behavior of this API?

    I currently cast the return value to int type and do the bit comparison to determin the key status as like:


    bool isShiftPressed = (int)coreWindow->GetKeyState(Windows::System::VirtualKey::Shift) & (int)Windows::UI::Core::CoreVirtualKeyStates::Down;


    This works, but the code doesn't look nice.

    What is the best practice to use GetKeyState() for checking if a key is pressed or not?


    Friday, December 7, 2012 1:48 PM


All replies

  • This is expected behavior. The CoreVirtualKeyStates are flags and so need to be checked as such by masking off ones you are interested in.


    Friday, December 7, 2012 11:21 PM
  • Hi Rob,


    I hope the API doc mentions this point explicitly. I think many developer misunderstand the usage of the API.

    Regarding the coding practice, I come up with the following for checking and storing the key state into the boolean variable:


    bool isShiftPressed = (bool)(sender->GetKeyState(Windows::System::VirtualKey::Shift) & Windows::UI::Core::CoreVirtualKeyStates::Down);


    There may be better way, but this is, I think, much better than the code snippet I attached before.


    Monday, December 10, 2012 1:53 AM