Windows C++ — Simplest Desktop Program

I’m much more of a Linux C++ developer, but here’s a quick start example of a CMake project that opens a window in Windows 10/11, gets keyboard input and is set up to draw something in the window:

main.cpp:

C++
#include <SDKDDKVer.h>
#include <windows.h>
#include <iostream>

// Window Event Handler
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        case WM_KEYDOWN:
            std::cout << "KEYDOWN" << std::endl;
            break;
        case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hWnd, &ps);
            // TODO: Add any drawing code that uses hdc here...
            EndPaint(hWnd, &ps);
        }
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                      _In_opt_ HINSTANCE hPrevInstance,
                      _In_ LPWSTR    lpCmdLine,
                      _In_ int       nCmdShow)
{

    // STEP 1 -- Create Window Class Name String
    LPCWSTR szWindowClass = L"MYWINDOWSDESKTOPPROJECT";

    // STEP 2 -- Setup the WNDCLASSEXW struct with the window parameters, so we can register the WNDCLASSEXW
    WNDCLASSEXW wcex;
    wcex.cbSize = sizeof(WNDCLASSEXW);

    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = NULL;
    wcex.hCursor = LoadCursorW(nullptr, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = szWindowClass;
    wcex.hIconSm = NULL;

    // STEP 3 -- Register the class
    RegisterClassExW(&wcex);

    // STEP 4 -- Create the Window
    HWND hWnd = CreateWindowExW(0L, szWindowClass, L"MyWindowsDesktopProject", WS_OVERLAPPEDWINDOW,
                              CW_USEDEFAULT, 0, 800, 600, nullptr, nullptr, hInstance, nullptr);
    if (!hWnd)
    {
        return FALSE;
    }

    // STEP 5 -- Show the window & tell it to draw the client area (UpdateWindow)
    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    // STEP 6 -- Main Loop -- Get Event (Message), Handle Event (Message)
    MSG msg;
    while (GetMessageW(&msg, nullptr, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int)msg.wParam;
}

CMakeLists.txt

CMake
cmake_minimum_required (VERSION 3.8)
project(win10desktop)

add_executable (win10desktop WIN32 main.cpp)

target_compile_definitions(win10desktop
        PRIVATE "UNICODE;_UNICODE"
        )

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *