输出文本

#include <windows.h>

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInst,
LPSTR lpszCmdLine,
int nCmdShow
)
{
MSG Msg;
HWND hwnd;
WNDCLASS wndclass;
char lpszClassName[] = "窗体";
//是这个窗口的类名wndclass,不是窗口左上角的那个
char lpszTitle[] = "My Window";
HBRUSH hbrush;
hbrush = CreateSolidBrush(RGB(0, 255, 0));//定义绿色画刷

wndclass.style = 0;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = hbrush;
//空值背景颜色,可用自定义画刷来调,绿色背景
wndclass.hInstance = hInstance;
wndclass.lpszClassName = lpszClassName;
wndclass.lpszMenuName = NULL;

if (!RegisterClass(&wndclass)) {
MessageBeep(0);
return 0;
}

hwnd = CreateWindow(
lpszClassName,
lpszTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL
);

ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);

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;//可以把hdc想象成画布
static long nXChar, nYChar; //定义x,y坐标
short x; //循环变量
TEXTMETRIC tm;//定义TEXTMETRIC结构,存放文本信息的结构体
short LnCount = 6; //
PAINTSTRUCT ps;//定义包含绘图信息的结构体变量

const char *textbuf[] = { //指针数组,重点
"This is the first line",
"This is the second line",
"This is the third line",
"This is the fourth line",
"This is the fifth line",
"This is the sixth line"
};
switch (message)
{
case WM_CREATE:
//处理窗口创建函数
hdc = GetDC(hwnd);
GetTextMetrics(hdc, &tm);
//获取字体信息放入tm结构体变量中
nXChar = tm.tmAveCharWidth; //从tm结构变量中获取字符宽度
nYChar = tm.tmHeight + tm.tmExternalLeading;
//获取换行时的y坐标
ReleaseDC(hwnd, hdc);//释放当前设备句柄
return 0;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
for (x = 0; x < LnCount; x++) //输出文本
TextOut(hdc, nXChar, nYChar * (1 + x), textbuf[x], lstrlen(textbuf[x]));
EndPaint(hwnd, &ps);
return 0; // 或者换成break;
case WM_DESTROY:
PostQuitMessage(0);
break;
//break很重要,没有的话窗口会址闪一下,因为直接执行完
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}

原文地址:https://www.cnblogs.com/nanfengnan/p/13731003.html