新建一个对话框程序并在对话框资源中加入一个静态文本框控件并更改其ID为IDC_MYSTATIC,
在OnPaint()函数中添加如下代码:
CWnd *pWnd = GetDlgItem(IDC_MYSTATIC);
CDC* pDC = pWnd->GetDC();
pWnd->Invalidate();
pWnd->UpdateWindow();
CRect scRect;
pWnd->GetClientRect(scRect);
COLORREF White = RGB(255, 255, 255);
CPen PenSolidWhite(PS_SOLID, 1, White); //宽1白色画笔
CPen PenDotWhite(PS_DOT, 1, White); //虚线
CBrush br;
br.CreateStockObject(NULL_BRUSH); //设置空画刷
pDC->SelectObject(&br); //选中空画刷
pDC->SelectObject(&PenSolidWhite); //选中白画笔
CRect rectCoord;
rectCoord.top = scRect.top + 30;
rectCoord.left = scRect.left + 40;
rectCoord.bottom = scRect.bottom - 30;
rectCoord.right = scRect.right - 40;
pDC->Rectangle(&rectCoord);
CString str;
int i;
int nxDivisionNum = 5;
int nyDivisionNum = 4;
int nxLength = rectCoord.right;
int nyLength = rectCoord.bottom;
int nxMeshLength, nyMeshLength;
nxMeshLength = (nxLength - 40) / (nxDivisionNum);
nyMeshLength = (nyLength - 30) / (nyDivisionNum);
CFont font;
font.CreateFont(10, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0,
ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _T("宋体"));
pDC->SelectObject(&PenSolidWhite); //选中1.0白画笔
pDC->SelectObject(&font);
pDC->SetTextColor(White);
pDC->SetBkMode(TRANSPARENT);
for (i=0; i < nxDivisionNum + 1; i++){
str.Format(_T("%4d"),i * 1000);
pDC->TextOut(23 + i * nxMeshLength, nyLength + 5, str);
}
for (i=0; i < nyDivisionNum + 1; i++){
str.Format(_T("%4d"),100 - i * 50);
pDC->TextOut(rectCoord.left - 25, 26 + i * nyMeshLength, str);
str.Format(_T("%d"),10000 - i * 5000);
pDC->TextOut(nxLength + 5, 26 + i * nyMeshLength, str);
}
pDC->SelectObject(PenDotWhite);
nxMeshLength /= 2;
for (i = 1; i < nxDivisionNum * 2; i++){
pDC->MoveTo(40 + nxMeshLength * i, 30);
pDC->LineTo(40 + nxMeshLength * i, nyLength);
}
for (i = 1; i < nyDivisionNum; i++){
pDC->MoveTo(40, 30 + nyMeshLength * i);
pDC->LineTo(nxLength, 30 + nyMeshLength * i);
}
PenDotWhite.DeleteObject();
PenSolidWhite.DeleteObject();
font.DeleteObject();
br.DeleteObject();
pDC->DeleteDC();
并打开"MFC类向导"对话框(VS2010按"Ctrl+Shift+X"组合键或者右键解决方案文件选择"类向导"或者在"资源视图"中打开对话框属性页)然后选择点击消息标签栏或按钮图标搜索或找到WM_CTLCOLOR点击它并添加处理程序, 添加好之后对话框cpp文件中就会添加**OnCtlColor()**函数, 在函数中添加如下代码以改变静态文本框背景色
if (pWnd->GetDlgCtrlID() == IDC_MYSTATIC){
hbr = CreateSolidBrush(RGB(0, 0, 0));
}