程式語言 - MinGW - C/C++ - Keyboard Event



參考資訊:
http://www.winprog.org/tutorial/
http://winapi.freetechsecrets.com/win32/
https://github.com/gammasoft71/Examples_Win32
http://masm32.com/board/index.php?topic=3584.0
https://learn.microsoft.com/en-us/windows/win32/winmsg/window-styles

WM_KEYDOWN、WM_KEYUP是一般鍵盤按鍵事件,而WM_SYSKEYDOWN、WM_SYSKEYUP則是屬於系統按鍵的事件,系統按鍵就是左上角小視窗圖案的那些按鍵命令

WM_KEYDOWN、WM_KEYUP

nVirtKey = (int) wParam; // virtual-key code
lKeyData = lParam;       // key data

WM_SYSKEYDOWN、WM_SYSKEYUP

nVirtKey = (int) wParam; // virtual-key code
lKeyData = lParam;       // key data

main.c

#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>

HWND hWin = NULL;
WNDPROC defWndProc = NULL;

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    char buf[255] = {0};

    switch (uMsg) {
    case WM_KEYDOWN:
    case WM_SYSKEYDOWN:
        sprintf(buf, "Key: %d", (int)wParam);
        SetWindowText(hWnd, buf);
        return 0;
    case WM_CLOSE:
        DestroyWindow(hWnd);
        return 0;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return CallWindowProc(defWndProc, hWnd, uMsg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    hWin = CreateWindow(WC_DIALOG, "main", 
        WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, 300, 300, NULL, NULL, NULL, NULL);
    defWndProc = (WNDPROC)SetWindowLongPtr(hWin, GWLP_WNDPROC, (long int)WndProc);

    MSG msg = {0};
    while (GetMessage(&msg, NULL, 0, 0)) {
        DispatchMessage(&msg);
    }
    ExitProcess(0);
    return 0;
}

Line 14~17:將按鍵數值顯示在視窗標題

編譯、執行

$ i686-w64-mingw32-gcc -mwindows main.c -o main.exe
$ wine ./main.exe