簡體   English   中英

Win32消息循環中的鍵盤輸入

[英]Keyboard Input in Win32 Message Loop

有沒有一種方法可以檢測消息循環內的鍵盤輸入。 這是我在下面嘗試過的方法:

LRESULT D3DApp::MsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch( msg )
    {     
    // WM_DESTROY is sent when the window is being destroyed.
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;

    case WM_KEYDOWN:
        BYTE keyboardState[256];

        if (keyboardState[DIK_W]) {
            OutputDebugStringW(L"W Button Pressed\n");
        }  

        if (keyboardState[DIK_A]) {
            OutputDebugStringW(L"A Button Pressed\n");
        } 

        if (keyboardState[DIK_S]) {
            OutputDebugStringW(L"S Button Pressed\n");
        } 

        if (keyboardState[DIK_D]) {
            OutputDebugStringW(L"D Button Pressed\n");
        }
        return 0;
    }
    return DefWindowProc(hwnd, msg, wParam, lParam);
}

問題是它似乎返回了所有鍵盤狀態:輸出如下...

W Button Pressed
A Button Pressed
S Button Pressed
D Button Pressed

我該如何實現它,使其僅檢測按下的按鍵輸入。 我是新手,所以這可能是一個愚蠢的實現:)

按下鍵時,您永遠不會設置元素。

您還將keyboardState數組用作局部變量。 您必須使其成為全局或靜態的,因為每次調用MsgProc函數時, MsgProc在堆棧上分配keyboardState ,並且不能保證其內容,該內容可能已被以前的函數調用使用相同的內存空間進行了修改。

在您的代碼中, keyboardState每個元素基本上都有255/256的可能性為非零,並且您正在檢測到的不是真正的按鍵。

如果您不是從外部訪問鍵盤狀態,請不要理會該數組-只需使用MsgProc函數的wParam參數MsgProc

 case WM_KEYDOWN:

    if (wParam == DIK_W) {
        OutputDebugStringW(L"W Button Pressed\n");
    }  

    if (wParam == DIK_A) {
        OutputDebugStringW(L"A Button Pressed\n");
    } 

    if (wParam == DIK_S) {
        OutputDebugStringW(L"S Button Pressed\n");
    } 

    if (wParam == DIK_D) {
        OutputDebugStringW(L"D Button Pressed\n");
    }
    return 0;

(假設您的DIK_密鑰值與WinAPI的VK_密鑰代碼相同)

您沒有在使用它之前初始化keyboardState

case WM_KEYDOWN:
{
    BYTE keyboardState[256];
    ::GetKeyboardState(keyboardState); // <-- ADD THIS!
    ...
    return 0;
}

或者,改用Get(Async)KeyState()

case WM_KEYDOWN:
{
    if (GetKeyState('W') & 0x8000) {
        OutputDebugStringW(L"W Button is Down\n");
    }  

    if (GetKeyState('A') & 0x8000) {
        OutputDebugStringW(L"A Button is Down\n");
    } 

    if (GetKeyState('S') & 0x8000) {
        OutputDebugStringW(L"S Button is Down\n");
    } 

    if (GetKeyState('D') & 0x8000) {
        OutputDebugStringW(L"D Button is Down\n");
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM