代碼
流程
在Windows上,一個窗口程序是由消息驅動的,所以創建一個窗口程序有如下幾個步驟:
- 註冊窗口類,包括
WNDCLASS
結構體的賦值以及RegisterClass
註冊窗口類 - 使用
CreateWindow
創建窗口以及ShowWindow
和UpdateWindow
更新顯示窗口 - 使用
GetMessage
和DispatchMessage
建立消息循環 - 完成處理消息的
WndProc
回調函數
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, int nCmdShow)
{
char *lpClassName = "FirstWin", *lpWindowName = "Title";
HWND hwnd;
MSG msg;
WNDCLASSEX wndclass;
wndclass.cbSize = sizeof(wndclass); // 指定該結構體的大小
wndclass.style = CS_HREDRAW | CS_VREDRAW; // 寬度高度變化時重繪
wndclass.lpfnWndProc = WndProc; // 窗口回調函數
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // NULL表示系統圖標,默認圖標
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); // 默認光標
wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); // 使用畫刷填充背景色,還可以(HBRUSH)GetStockObject(BLACK_BRUSH)
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = lpClassName;
wndclass.hIconSm = NULL;
if (!RegisterClassEx(&wndclass))
{
MessageBox(NULL, "Register Failed", "Tips", MB_ICONERROR);
return 0;
}
hwnd = CreateWindow(lpClassName,
lpWindowName,
WS_OVERLAPPEDWINDOW, //style
CW_USEDEFAULT, // x
CW_USEDEFAULT, // y
600, // width
400, // height
NULL, // hWndParent
NULL, // hMenu
hInstance, // hInstance
NULL);
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd); // 發送 WM_PAINT,保證窗口一定可以刷新顯示
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT rect;
switch (message)
{
case WM_CREATE:
MessageBox(NULL, "Create Windows Success", "Tips", MB_OK);
break;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &rect);
DrawText(hdc, "HelloWorld", -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
EndPaint(hwnd, &ps);
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
使用gcc -m32 -mwindows win1.c -o win1.exe
編譯
運行結果