代码
流程
在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
编译
运行结果