4

タイマーでキーステートをチェックする必要がある C++ (MFC) アプリがあります。ユーザーがキーを押している場合、一部のコードの処理を遅らせます。

のチェックは次のkeydownとおりです。

if (!GetKeyboardState(keyState)) 
{
    s_executeDeferredResult = e_executeDeferredButtonCheckFailed;
    return;
}   
s_executeDeferredStuckKeys.clear();
for (int index=0; index<arrsize(keyState); ++index)
{
    if (keyState[index] & 0x80)
    {
        s_executeDeferredStuckKeys.insert(index);
    }
}
if (!s_executeDeferredStuckKeys.empty())
{
    s_executeDeferredResult = e_executeDeferredButtonsActive;
    return;
}

ただし、スタックするキー コンボがいくつかあります。

  1. オンにするNUMLOCK
  2. プレスSHIFT
  3. プレスNumPad8
  4. リリースSHIFT
  5. リリース(NumPad8
    これは一例です。他にもあります。他にもありCTRLます。ALTDEL

GetKeyboardStateVK_UPが押されたことを報告します。

発生するイベントは (上記のアクションに対応) です。

  1. <None>
  2. WM_KEYDOWNVK_SHIFT
  3. WM_KEYUPVK_SHIFT
    WM_KEYDOWNVK_UP
    WM_KEYDOWNVK_SHIFT
  4. WM_KEYUPVK_SHIFT
  5. WM_KEYUPVK_NUMPAD8

そのため、Windows は Up キーが上がったことを認識せず、現在GetKeyboardStateは壊れています。

キーの実際の状態を確認する良い方法はありますか? GetAsyncKeyStateどちらも、キーもダウンしているとGetKeyState報告しています。

4

1 に答える 1

2

解決しました。

InitInstance のキーボード イベントにフックし、スキャン コード (スキャン コードをキーとし、仮想キーを値とするマップ) によって浮き沈みを追跡しています。

m_keyboardHook = SetWindowsHookEx(WH_KEYBOARD, &KeyboardHook, NULL, GetCurrentThreadId());

static LRESULT CALLBACK KeyboardHook(
    __in int nCode,
    __in WPARAM wParam,
    __in LPARAM lParam
    )
{
    // According to the docs, we're not allowed to do any "further processing" if nCode is < 0.
    // According to the docs, we should process messages if we get code HC_ACTION. 
    // http://msdn.microsoft.com/en-us/library/windows/desktop/ms644984(v=vs.85).aspx
    // It doesn't specify what to do if another code comes in, so we will just ignore any other codes.
    if (nCode == HC_ACTION)
    {
        uint8 scanCode = (uint8)((lParam & 0x00FF0000) >> 16);
        uint8 virtKey = (uint8)wParam;
        if (lParam & 0x80000000) // key up
            KeyState::SetKeyUp(scanCode);
        else
            KeyState::SetKeyDown(scanCode, virtKey);
    }

    // We must call the next hook in the chain, according to http://msdn.microsoft.com/en-us/library/windows/desktop/ms644975%28v=vs.85%29.aspx
    // First param is ignored, according to http://msdn.microsoft.com/en-us/library/windows/desktop/ms644974%28v=vs.85%29.aspx )
    return CallNextHookEx(0, nCode, wParam, lParam);
}

したがって、私の遅延チェックは次のようになります。

// Similarly, don't process deferred events if there are keys or mouse buttons which are currently down.
s_executeDeferredStuckKeys.clear();
if (KeyState::AnyKeysDown(s_excludeKeys, arrsize(s_excludeKeys)))
{
    s_executeDeferredResult = e_executeDeferredButtonsActive;
    KeyState::GetDownKeys(s_executeDeferredStuckKeys);
    return;
}
于 2013-08-29T18:31:40.390 に答える