How to create a window and add custom icon to the windows with C++ Win32 API

1 Answer

0 votes
// First - Add icon to Resource Files in Solution Explorer: Add - Resource...

#include <windows.h>

#include "resource.h" // IDI_ICON2 or IDI_ICON1 - Depend on the number of icons you added

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 = static_cast<HICON>(LoadImage(hInstance,
		MAKEINTRESOURCE(IDI_ICON2),
		IMAGE_ICON, 32, 32, 0));
	wc.hCursor = NULL;
	wc.hbrBackground = NULL;
	wc.lpszMenuName = NULL;
	wc.lpszClassName = szClassName;
	wc.hIconSm = static_cast<HICON>(LoadImage(hInstance,
		MAKEINTRESOURCE(IDI_ICON2),
		IMAGE_ICON, 16, 16, 0));

	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;
	}

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

 



answered Jan 17, 2023 by avibootz
...