設置 | 登錄 | 註冊

作者共發了4篇帖子。

【代碼】C++編寫的最基本的Win32窗口程序

1樓 巨大八爪鱼 2015-12-4 22:47
【運行結果】


【頭文件 Main.h】
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow);
LRESULT CALLBACK WndProcedure(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

【源文件 Main.c】
#include <Windows.h>
#include "Main.h"

LPCTSTR ClsName = L"BasicApp";
LPCTSTR WndName = L"A Simple Window";

INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    MSG Msg;
    HWND hWnd;
    WNDCLASSEX WndClsEx;
   
    // Create the application window
    WndClsEx.cbSize = sizeof(WNDCLASSEX);
    WndClsEx.style = CS_HREDRAW | CS_VREDRAW;
    WndClsEx.lpfnWndProc = WndProcedure;
    WndClsEx.cbClsExtra = 0;
    WndClsEx.cbWndExtra = 0;
    WndClsEx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    WndClsEx.hCursor = LoadCursor(NULL, IDC_ARROW);
    WndClsEx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    WndClsEx.lpszMenuName = NULL;
    WndClsEx.lpszClassName = ClsName;
    WndClsEx.hInstance = hInstance;
    WndClsEx.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

    // Register the application
    RegisterClassEx(&WndClsEx);

    // Create the window object
    hWnd = CreateWindow(ClsName, WndName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
    // Find out if the window was created
    if (!hWnd) // If the window was not created
        return 0; // stop the application

    // Display the window to the user
    ShowWindow(hWnd, SW_SHOWNORMAL);
    UpdateWindow(hWnd);

    // Decode and treat the messages
    // as long as the application is running
    while (GetMessage(&Msg, NULL, 0, 0))
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }

    return Msg.wParam;
}

LRESULT CALLBACK WndProcedure(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    switch (Msg)
    {
    case WM_DESTROY:
        // If the user wants to close the application
        // then close it
        PostQuitMessage(WM_QUIT);
        break;
    default:
        // Process the left-over messages
        return DefWindowProc(hWnd, Msg, wParam, lParam);
    }
    // If something was not done, let it go
    return 0;
}
2樓 巨大八爪鱼 2015-12-4 22:48
3樓 巨大八爪鱼 2016-1-4 14:30
整個流程簡單概括如下:
第一步:創建窗口類,其中包含hInstance和ClsName
第二步:註冊窗口類
第三步:用ClsName創建窗口
第四步:顯示窗口並首次繪製窗口內容
然後就是消息循環,在消息循環中讓系統不停地調用WndProcedure(這個函數是在窗口類中指定的)來處理Windows消息。消息循環結束後,退出程序,將Msg.wParam作為返回值返回給作業系統。

我們在調用CreateWindow創建窗口時,提供的參數是窗口類的名稱字符串,而不是窗口類結構體本身。這就是為什麼我們要向作業系統註冊窗口類的原因。
4樓 巨大八爪鱼 2016-1-4 14:40
另外,當應用程式收到WM_DESTROY消息時,窗口已經被關閉了。執行PostQuitMessage(WM_QUIT)這句話只是為了退出消息循環而已。在Visual Studio中創建的Win32程序中,這句話是這樣寫的:PostQuitMessage(0),括號中就是想要在程序退出時return語句返回給作業系統的值(Msg.wParam)。

內容轉換:

回覆帖子
內容:
用戶名: 您目前是匿名發表。
驗證碼:
看不清?換一張
©2010-2025 Purasbar Ver3.0 [手機版] [桌面版]
除非另有聲明,本站採用知識共享署名-相同方式共享 3.0 Unported許可協議進行許可。