Keyboard Input Example
#include <windows.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
const wchar_t CLASS_NAME[] = L"MyWindowClass";
WNDCLASSEXW wc = {0};
MSG msg;
// Register the window class
wc.cbSize = sizeof(WNDCLASSEXW);
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
wc.lpszClassName = CLASS_NAME;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassExW(&wc))
return 0;
HWND hwnd = CreateWindowExW(
WS_EX_CLIENTEDGE,
CLASS_NAME,
L"Keyboard Input Demo",
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
700,
350,
NULL,
NULL,
hInstance,
NULL);
if (!hwnd)
return 0;
// Message loop
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return static_cast<int>(msg.wParam);
}
LRESULT CALLBACK WndProc(HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam)
{
static wchar_t key[64] = L"";
static wchar_t chr[64] = L"";
static int keyLen = 0;
static int chrLen = 0;
switch (msg)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
TextOutW(hdc, 10, 10, key, keyLen);
TextOutW(hdc, 10, 35, chr, chrLen);
EndPaint(hwnd, &ps);
return 0;
}
case WM_KEYDOWN:
{
keyLen = wsprintfW(
key,
L"Virtual-Key Code: 0x%02X (%u)",
(UINT)wParam,
(UINT)wParam);
InvalidateRect(hwnd, NULL, TRUE);
return 0;
}
case WM_CHAR:
{
chrLen = wsprintfW(
chr,
L"Character: %lc (0x%04X)",
(wchar_t)wParam,
(UINT)wParam);
InvalidateRect(hwnd, NULL, TRUE);
return 0;
}
case WM_CLOSE:
DestroyWindow(hwnd);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProcW(hwnd, msg, wParam, lParam);
}