获取HDC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_PAINT :
PAINTSTRUCT ps;
HDC hdc;
hdc = BeginPaint(hWnd, &ps);

RECT rect;
GetClientRect (hWnd, &rect);

paintOperator(hdc, rect.left, rect.top, rect.right, rect.bottom);

EndPaint(hWnd, &ps);
break;
case WM_DESTROY :
PostQuitMessage(0); // 发出 WM_QUIT 消息,没有这句话则只是关闭窗口但进程不会停止
break;
default :
return DefWindowProc(hWnd, message, wParam, lParam); // 默认时采用系统消息默认处理函数
}

return 0;
}

画笔

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
HPEN hp;
hp = (HPEN) GetStockObject(BLACK_PEN); // 默认画笔
SelectObject(hdc, hp);

MoveToEx(hdc,x,y,NULL);
LineTo(hdc,x,y); // 画直线,需要先移动点的位置

Ellipse(hdc, L, T, R, B); // 画椭圆

hp = (HPEN) CreatePen(PS_SOLID, 3, RGB(0xFF, 0, 0)); // 自定义画笔
SelectObject(hdc, hp);
POINT lpPoints[4] = { {L, B}, {R, B}, {(L+R)/2, T}, {L, B} }; // 三角形的点
Polyline(hdc, lpPoints, 4); // 画点数组

DeleteObject(hp); // 别忘了CreatePen后要手动删除

画刷

1
2
3
4
HBRUSH hbr = (HBRUSH) CreateSolidBrush(RGB(color[pos][0], color[pos][1], color[pos][2]));
SelectObject(hdc, hbr);
Rectangle(hdc, L, T, R, B);
DeleteObject(hbr);

字体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
HFONT hf;
TEXTMETRIC tm;
char * str[5] = {"HELLO WORLD!", "", ""};

hf = CreateFont(0, 0, 0, 0, 0, 0, 0, 0, 0, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, "楷体"); // (HFONT) GetStockObject(0) // 创建字体
SelectObject(hdc, hf);
SetTextColor(hdc, 0x0000FF/*BGR*/); // 选择颜色
GetTextMetrics(hdc, &tm); // 获取字体属性:宽高

double len = strlen(str[0]) * tm.tmAveCharWidth; // 字体长度
int left = (R-W/2) - len/2; // 居中靠上显示,获取左边坐标
TextOut(hdc, left, 0, str[0], strlen(str[0])); // 输出

DeleteObject(hf);
double cheight += tm.tmHeight; // 当前字体的高度,以便于下一行
double cwidth = tm.tmAveCharWidth;