模組 1. 您的第一個 Windows 程式

在此課程模組中,我們將撰寫最小的 Windows 桌面程式。 其全部都是建立並顯示空白視窗。 第一個套裝程式含大約 50 行的程式碼,不會計算空白行和批註。 這會是我們起點;稍後我們將新增圖形、文字、使用者輸入和其他功能。

如果您想要深入瞭解如何在 Visual Studio 中建立傳統 Windows 傳統型應用程式,請參閱逐步解說 :建立傳統 Windows 傳統型應用程式 (C++)

範例程式的螢幕擷取畫面,其中顯示它是空白視窗,標題為 Learn to Program Windows。

以下是程式的完整程式碼:

#ifndef UNICODE
#define UNICODE
#endif 

#include <windows.h>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
    // Register the window class.
    const wchar_t CLASS_NAME[]  = L"Sample Window Class";
    
    WNDCLASS wc = { };

    wc.lpfnWndProc   = WindowProc;
    wc.hInstance     = hInstance;
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    // Create the window.

    HWND hwnd = CreateWindowEx(
        0,                              // Optional window styles.
        CLASS_NAME,                     // Window class
        L"Learn to Program Windows",    // Window text
        WS_OVERLAPPEDWINDOW,            // Window style

        // Size and position
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,

        NULL,       // Parent window    
        NULL,       // Menu
        hInstance,  // Instance handle
        NULL        // Additional application data
        );

    if (hwnd == NULL)
    {
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);

    // Run the message loop.

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

    return 0;
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;

    case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hwnd, &ps);

            // All painting occurs here, between BeginPaint and EndPaint.

            FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW+1));

            EndPaint(hwnd, &ps);
        }
        return 0;

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

您可以從Windows Hello World Sample下載完整的 Visual Studio 專案。

提供此程式碼用途的簡短大綱可能很有用。 稍後的主題會詳細檢查程式碼。

  1. wWinMain 是程式進入點。 當程式啟動時,它會註冊應用程式視窗行為的一些相關資訊。 其中一個最重要的專案是函式的位址,在此範例中命名 WindowProc 。 此函式會定義視窗的行為—其外觀、其與使用者互動的方式等等。
  2. 接下來,程式會建立視窗,並接收可唯一識別視窗的控制碼。
  3. 如果已成功建立視窗,程式就會進入 while 迴圈。 程式會保留在這個迴圈中,直到使用者關閉視窗並結束應用程式為止。

請注意,即使我們說這是定義大部分應用程式邏輯的地方,程式也不會明確呼叫 WindowProc 函式。 Windows 會透過傳遞一系列 訊息來與您的程式通訊。 while迴圈中的程式碼會驅動此程式。 每次程式呼叫 DispatchMessage 函式時,都會間接讓 Windows 針對每個訊息叫用 WindowProc 函式一次。

本節內容

瞭解如何以 C++ 撰寫適用于 Windows 的程式

Windows Hello世界範例