Search code examples
c++xamlwinui-3

How do I know if a key is pressed in WinUI 3/WinAppSDK (CoreWindow.GetKeyState alternatives)?


In my old UWP apps, I could check a keyboard key's state in my handlers, like this:

void MyControl::UserControl_KeyDown(winrt::IInspectable const& /*sender*/, winrt::KeyRoutedEventArgs const& e)
{
    if (e.Key() == winrt::VirtualKey::F6)
    {
        const auto isShiftPressed = winrt::CoreWindow::GetForCurrentThread().GetKeyState(winrt::VirtualKey::Shift) & winrt::CoreVirtualKeyStates::Down;
        // ...
    }
}

But winrt::CoreWindow::GetForCurrentThread() returns null in WinUI 3. How do I get keyboard states in my code?


Solution

  • The official docs (Windows Runtime APIs not supported in desktop apps) recommend InputKeyboardSource.GetKeyStateForCurrentThread instead:

    [...]Instead of the GetKeyState method, use the InputKeyboardSource.GetKeyStateForCurrentThread method provided by WinUI 3.

    void MyControl::UserControl_KeyDown(winrt::IInspectable const& /*sender*/, winrt::KeyRoutedEventArgs const& e)
    {
        if (e.Key() == winrt::VirtualKey::F6)
        {
            const auto isShiftPressed = winrt::InputKeyboardSource::GetKeyStateForCurrentThread(winrt::VirtualKey::Shift) & winrt::CoreVirtualKeyStates::Down;
            // ...
        }
    }
    

    See my similar question about getting the UI thread in WinUI 3.