由之前彩色随机矩形线条获得启发,今日学习文字输出时,使用随机色定义字体颜色,获得彩色变换文字输出。
//随机字体颜色
SetTextColor(g_hdc, RGB(rand() % 256, rand() % 256, rand() % 256));
由于WM_PAINT消息目前仅在窗口大小发生改变时触发,故获得炫彩效果需拖动窗口边框。
在定位字体位置时,观察到TextOut()函数输出位置定位在字符串左上角。同时发现通过MoveWindow()函数设置窗口位置、大小时,设置的大小为窗口区大小,并非之前以为的客户区大小。之后会检索窗口区大小的设置问题。
为求基本框架熟记,以及提高代码书写水平,每次新建项目书写基本框架均使用手打方式,不采用复制之前框架的做法。
源代码:
/*
学习使用GDI文字输出
2017/08/19
*/
//头文件
#include <Windows.h>
#include <time.h> //生成随机数
//全局函数声明
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam,
LPARAM lParam);
bool Game_Init(HWND hwnd);
void Game_Paint(HWND hwnd);
bool Game_Cleanup(HWND hwnd);
//全局变量
HDC g_hdc = 0;
//入口函数
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
//创建窗口类
WNDCLASSEX wndClass = { 0 };
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.cbSize = sizeof(WNDCLASSEX);
wndClass.hbrBackground = (HBRUSH)GetStockObject(GRAY_BRUSH);
wndClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
wndClass.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
wndClass.hInstance = hInstance;
wndClass.lpfnWndProc = WndProc;
wndClass.lpszClassName = L"GDI_Text";
wndClass.lpszMenuName = nullptr;
wndClass.style = CS_HREDRAW | CS_VREDRAW;
//注册窗口类
if ( !RegisterClassEx(&wndClass) )
{
MessageBox(nullptr, L"窗口类创建失败!", L"", MB_OK);
return -1;
}
//创建窗口
HWND hwnd = CreateWindow(L"GDI_Text", L"文字输出演示", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, hInstance,
nullptr);
//显示刷新窗口
ShowWindow(hwnd, nCmdShow);
MoveWindow(hwnd, 0, 0, 800, 600, true);
UpdateWindow(hwnd);
Game_Init(hwnd);
//消息循环
MSG msg = { 0 };
while (msg.message!=WM_QUIT)
{
if (PeekMessage(&msg,0,0,0,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
//注销窗口类
UnregisterClass(L"GDI_Text", hInstance);
return 0;
}
//全局函数定义
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam,
LPARAM lParam)
{
PAINTSTRUCT paintstruct;
switch (message)
{
//如果窗口刷新,调用Game_Paint重绘画面
case WM_PAINT:
g_hdc = BeginPaint(hwnd, &paintstruct);
Game_Paint(hwnd);
EndPaint(hwnd, &paintstruct);
ValidateRect(hwnd, nullptr);
break;
case WM_CLOSE:
if (IDYES == MessageBox(hwnd, L"是否退出程序?", L" ", MB_YESNO))
DestroyWindow(hwnd);
break;
case WM_DESTROY:
Game_Cleanup(hwnd);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
}
bool Game_Init(HWND hwnd)
{
//设置随机数种子
srand((unsigned)time(nullptr));
Game_Paint(hwnd);
return true;
}
void Game_Paint(HWND hwnd)
{
g_hdc = GetDC(hwnd);
wchar_t text1[] = L"我就试试";
//设置字体
HFONT hFont = CreateFont(80, 0, 0, 0, 0, 0, 0, 0, GB2312_CHARSET, 0, 0, 0, 0,
L"幼圆");
SelectObject(g_hdc, hFont);
//设置字体透明背景
SetBkMode(g_hdc, TRANSPARENT);
//随机字体颜色
SetTextColor(g_hdc, RGB(rand() % 256, rand() % 256, rand() % 256));
TextOut(g_hdc, 0, 50, text1, wcslen(text1));
ReleaseDC(hwnd, g_hdc);
}
bool Game_Cleanup(HWND hwnd)
{
return true;
}