winapi没有回应按键

时间:2017-01-08 17:30:05

标签: c++ winapi

我最近决定学习一点WinApi,但我遇到了麻烦。我想在按键后在窗口显示按摩,但它似乎不起作用。如果我多次按键或者按下它,仍然没有任何反应。你能告诉我我做错了吗?

这是完整的代码:

#include <windows.h>
#include <string.h>
#include <stdlib.h>
#include <tchar.h>

LRESULT CALLBACK WndProc (HWND   hwnd,
                          UINT   uMsg,
                          WPARAM wParam,
                          LPARAM lParam)
{
    PAINTSTRUCT ps;
    HDC hdc;
    LPCWSTR display_str = L"hello";
    switch(uMsg)
    {
        case WM_PAINT:
            hdc = BeginPaint(hwnd, &ps);
            if(GetAsyncKeyState(VK_UP))
            {
            TextOut(hdc,
                    15, 15,
                    display_str,
                    _tcslen(display_str));
            }
            EndPaint(hwnd, &ps);
            break;

        case WM_CLOSE:
            DestroyWindow(hwnd);
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    HWND hwnd;
    MSG uMsg;
    HINSTANCE hInst;
    WNDCLASSEX wcex;
    LPCWSTR class_name = L"myWindowClass";

    wcex.cbSize         = sizeof(WNDCLASSEX);
    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = class_name;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));

    if(!RegisterClassEx(&wcex))
    {
        MessageBox(NULL, L"Call to RegisterClassEx failed!", L"Win32 Guided Tour!",
        MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    hInst = hInstance;

    hwnd = CreateWindowEx(
        NULL,
        class_name,
        L"Test",
        WS_OVERLAPPEDWINDOW,
        200, 200,
        740, 540,
        NULL,
        NULL,
        hInstance,
        NULL
        );

    if(!hwnd)
    {
        MessageBox(NULL, L"Window Creation Failed!", L"Error!",
        MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while(GetMessage(&uMsg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&uMsg);
        DispatchMessage(&uMsg);
    }
    return uMsg.wParam;
}

2 个答案:

答案 0 :(得分:1)

按下某个键时,Windows会发送WM_KEYDOWN消息。在WndProc处理WM_KEYDOWN消息中,使用窗口的Client rect调用InvalidateRect并绘制要在WM_PAINT消息处理程序中显示的文本。

答案 1 :(得分:1)

这是我的示例,如果按F11键,则在控制台字符串中打印。:

case WM_KEYDOWN:
     if(wParam==VK_F11)
     {
           std::cout << "Hello in my example!";
     }

break;