Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to create a window and use KEYDOWN and KEYUP with specific keyboard letter key in C++ Win32 API

1 Answer

0 votes
#include <windows.h>

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int CALLBACK WinMain(
	HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR     lpCmdLine,
	int       nCmdShow) {

	static TCHAR szClassName[] = L"directx12";

	WNDCLASSEX wc = { 0 };
	wc.cbSize = sizeof(wc);
	wc.style = CS_OWNDC;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = NULL;
	wc.hCursor = NULL;
	wc.hbrBackground = NULL;
	wc.lpszMenuName = NULL;
	wc.lpszClassName = szClassName;
	wc.hIconSm = NULL;

	if (!RegisterClassEx(&wc)) {
		MessageBox(NULL, L"RegisterClassEx Error", L"Title", MB_ICONEXCLAMATION | MB_OK);
		return 1;
	}

	HWND hWnd = CreateWindowEx(
		0, szClassName, L"Window Name",
		WS_CAPTION | WS_MAXIMIZEBOX | WS_SYSMENU | WS_MINIMIZEBOX,
		300, 300, 640, 480,
		NULL, NULL, hInstance, NULL);

	if (!hWnd) {
		MessageBox(NULL, L"hWnd Error", L"Title", MB_ICONEXCLAMATION | MB_OK);
		return 1;
	}

	ShowWindow(hWnd, SW_SHOW);
	UpdateWindow(hWnd);

	MSG msg = {0};
	BOOL result;
	while ( (result = GetMessage(&msg, NULL, 0, 0)) ) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	if (result == -1)
		return -1;

	return (int)msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
	switch (uMsg) {
		case WM_CLOSE:
			PostQuitMessage(69);
			break;
		case WM_KEYDOWN:
			if (wParam == 'F') {
				SetWindowText(hWnd, L"Test");
			}
			break;
		case WM_KEYUP:
			if (wParam == 'F') {
				SetWindowText(hWnd, L"C++");
			}
			break;
	}

	return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

 



answered Dec 14, 2022 by avibootz
...