在C++中創建窗口程序的步驟如下:
導入相關頭文件:
#include <windows.h>
聲明窗口過程函數:
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
在主函數中注冊窗口類并創建窗口:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 1. 定義窗口類
WNDCLASS wc = {0};
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszClassName = "WindowClass";
// 2. 注冊窗口類
RegisterClass(&wc);
// 3. 創建窗口
HWND hwnd = CreateWindow("WindowClass", "Hello, World!", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 500, 500, NULL, NULL, hInstance, NULL);
// 4. 顯示窗口
ShowWindow(hwnd, nCmdShow);
// 5. 消息循環
MSG msg = {0};
while(GetMessage(&msg, NULL, 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;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
以上是一個簡單的窗口程序的基本框架,你可以根據需求在窗口過程函數中處理各種消息,實現不同的功能。