框架

/* -------------------------------------------------------------------
MyWindows.c -- 基本窗口模型
《Windows 程序设计(SDK)》视频教程
--------------------------------------------------------------------*/
#include
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
/*--------------------------------------------------------------------
hInstance : 应用程序当前实例句柄
hPrevInstance : 应用程序先前实例的句柄, 对于32为程序, 该参数总为NULL
szCmdLind : 指向应用程序命令行的字符串的指针
iCmdShow : 指明窗口如何显示, 可以在ShowWindow()中使用
----------------------------------------------------------------------*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT("MyWindows"); //窗口类的名字
HWND hwnd; //窗口句柄
MSG msg; //消息
WNDCLASS 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); //设置图标
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); //设置鼠标光标
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); //设置背景颜色
wndclass.lpszMenuName = NULL; //设置菜单
wndclass.lpszClassName = szAppName; //窗口类名字
// 注册窗口
if (!RegisterClass(&wndclass))
{
MessageBox(NULL, TEXT("需要 windows NT 环境"), szAppName, MB_ICONERROR);
return 0;
}
// 创建窗口类
hwnd = CreateWindow(szAppName, //窗口类的名称
NULL, // 窗口标题
WS_OVERLAPPEDWINDOW, // 水平滚动条, 垂直滚动条
200, // 初始x坐标, 默认值
200, // 初始y坐标
400, // 初始x方向尺寸
120, // 初始y方向尺寸
NULL, // 父窗口句柄
NULL, // 窗口菜单句柄
hInstance, // 程序实例句柄
NULL // 创建参数
);
ShowWindow(hwnd, iCmdShow); //显示窗口
UpdateWindow(hwnd); //更新窗口
// 消息循环
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
// 回调函数,由windows调用
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT rect;
switch (message)
{
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &rect);
DrawText(hdc, TEXT("大家好,这是我的第一个窗口程序!"), -1, &rect,
DT_SINGLELINE | DT_CENTER | DT_VCENTER);
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}

顺序

窗口类结构

注册窗口类

创建窗口实例

显示窗口

更新窗口

消息循环

PeekMessage(); // 无论是否获取到消息,都会返回, 可以对框架作如下修改
while (TRUE)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
// 程序空闲时间处理
}
}