【问题标题】:How to detect down/up event of special keys on the keyboard如何检测键盘上特殊键的向下/向上事件
【发布时间】:2015-08-28 11:58:37
【问题描述】:

我的环境是 Windows 10 64 位上的 Visual Studio 2013。

在我的 Windows 应用商店应用程序(适用于 Windows 8.1)中,我附加了这样的键盘事件(这是一个 c++/cx 程序,因为我使用的是 C++ 工具包):

auto amv = Windows::ApplicationModel::Core::CoreApplication::MainView;
if (amv){
    auto cw = amv->CoreWindow;
    if (cw){
        cw->KeyDown += ref new TypedEventHandler<CoreWindow ^, KeyEventArgs^>(srt, &WinRTApp::OnKeyDown);
        cw->KeyUp += ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(srt, &WinRTApp::OnKeyUp);
    }
}

当我按下日文 (109) 键盘上的 Hankaku 键时。系统使用未定义的 VirtualKey 代码(243)触发 KeyUp 事件,使用代码 244 触发 KeyDown 事件。当我释放该键时,没有触发任何事件。

第二次按下触发KeyUp(244)和KeyDown(243),第二次释放没有触发。

我想准确检测 KeyUp 事件。有什么好的方法吗?

【问题讨论】:

    标签: c# c++ windows-runtime windows-store-apps keyboard-events


    【解决方案1】:

    我研究了您的问题,发现了一种相当简单的方法来处理每次按键事件,而不管字符值如何。在 Onlaunched 事件中,您可以在 App.xaml.cpp 中添加事件处理程序,也可以将其添加到特定页面,例如。 MainPage.xaml.cpp

    Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->KeyUp += ref new Windows::Foundation::TypedEventHandler<Windows::UI::Core::CoreWindow ^, Windows::UI::Core::KeyEventArgs ^>(this, &KeyUpTest::App::OnKeyUp);
    

    在事件处理程序本身中简单地使用

    void KeyUpTest::App::OnKeyUp(Windows::UI::Core::CoreWindow ^sender,       Windows::UI::Core::KeyEventArgs ^args)
    {
    
    }
    

    每次发生非系统键时都会触发。您可以对 bool 数组的多个键状态使用相同的过程。

    更多信息可以在这里找到:http://www.cplusplus.com/forum/windows/117293/

    KeyUp 和 KeyDown 命令存在许多问题,它们返回的是按下的键的值,而不是所选字符的值,例如:

    如果我按 7,响应是 55,如果我按 shift 7,答案仍然是 55,而不是 & 的值。您可能正在寻找的是 CharacterReceived 事件,它提供更多上下文并处理大小写和其他值。

    要添加此事件,您可以使用

    Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->CharacterReceived += ref new Windows::Foundation::TypedEventHandler<Windows::UI::Core::CoreWindow ^, Windows::UI::Core::CharacterReceivedEventArgs ^>(this, &KeyUpTest::App::OnCharacterReceived);
    

    处理程序看起来像:

    void KeyUpTest::App::OnCharacterReceived(Windows::UI::Core::CoreWindow ^sender, Windows::UI::Core::CharacterReceivedEventArgs ^args)
    {
        bool iskey = false;
        int keycode = args->KeyCode;
    
        if (keycode == 65) {
            iskey = true;
        }
    }
    

    我希望这会有所帮助。

    【讨论】:

    • 字母键没有问题。 Hankaku 密钥不适用于该解决方案。
    猜你喜欢
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2020-10-10
    • 2015-05-25
    • 2010-09-21
    相关资源
    最近更新 更多