这一章节主要讲解了文本相关的一些编程
插入符的使用
CreateSolidCaret(100,200);//插入符的宽度和高度
ShowCaret();
插入符的一般使用方法
int CTestView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)
return -1; // TODO: Add your specialized creation code here
//CreateSolidCaret(20,100);
//ShowCaret(); CClientDC dc(this);
//定义文本结构变量
TEXTMETRIC tm;
//获取设备描述表中的文本信息
dc.GetTextMetrics(&tm);
//根据文本大小创建合适的光标
CreateSolidCaret(tm.tmAveCharWidth/8,tm.tmAveCharWidth); //实践下来这样显示的光标还是看上去不合理tm.tmAveCharWidth*2看上去还行
//显示光标
ShowCaret(); SetTimer(5,100,NULL);
return 0;
}
当窗口的大小发生变化时,显示窗口里的内容会消失,是由于OnDraw函数
void CTestView::OnDraw(CDC* pDC)
{
CTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
CString str("VC++深入详解");
pDC->TextOut(50,50,str); CSize cz = pDC->GetTextExtent(str); str.LoadString(IDS_STRING61446);
pDC->TextOut(0,200,str);
//路径层
pDC->BeginPath();
pDC->Rectangle(50,50,50+cz.cx,50+cz.cy);
pDC->EndPath();
//裁剪区域
pDC->SelectClipPath(RGN_DIFF);
//绘制网格
for (int i = 0; i < 300; i+=10)
{
pDC->MoveTo(0,i);
pDC->LineTo(300,i);
pDC->MoveTo(i,0);
pDC->LineTo(i,300);
}
}
下面是关于字符输入的demo
void CTestView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// TODO: Add your message handler code here and/or call default
CClientDC dc(this);
CFont font;
font.CreatePointFont(300,"华文行楷",NULL);
CFont *pOldFont = dc.SelectObject(&font);
TEXTMETRIC tm;
dc.GetTextMetrics(&tm);
if(0x0d == nChar) //如果是回车键
{
m_strLine.Empty();
m_ptOrign.y += tm.tmHeight;
}
else if (0x08 == nChar)//如果是后退键
{
COLORREF clr = dc.SetTextColor(dc.GetBkColor()); //删除的实现方法:设置字符串颜色为窗体背景颜色
dc.TextOut(m_ptOrign.x,m_ptOrign.y,m_strLine); //输出字符串
m_strLine = m_strLine.Left(m_strLine.GetLength()-1); //去除字符串的末端字符
dc.SetTextColor(clr); //去除末端字符后颜色还原
}
else
{
m_strLine += nChar;
}
//光标跟随字符后面
CSize sz = dc.GetTextExtent(m_strLine);
CPoint pt;
pt.x = m_ptOrign.x + sz.cx;
pt.y = m_ptOrign.y;
SetCaretPos(pt);
dc.TextOut(m_ptOrign.x,m_ptOrign.y,m_strLine);
dc.SelectObject(pOldFont);
CView::OnChar(nChar, nRepCnt, nFlags);
}
定时器的应用,在onCreate函数里添加 SetTimer(1,100,NULL);
具体实现如下
void CTestView::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
m_nWidth += 5;
CClientDC dc(this);
TEXTMETRIC tm;
dc.GetTextMetrics(&tm);
CRect rect;
rect.left = 0;
rect.top = 200;
rect.right = m_nWidth;
rect.bottom = rect.top + tm.tmHeight; dc.SetTextColor(RGB(255,0,0));
CString str;
str.LoadString(IDS_STRING61446);
dc.DrawText(str,rect,DT_LEFT); rect.top = 150;
rect.bottom = rect.top + tm.tmHeight;
dc.DrawText(str,rect,DT_RIGHT); CSize sz = dc.GetTextExtent(str);
if(m_nWidth > sz.cx)
{
m_nWidth = 0;
dc.SetTextColor(RGB(0,255,0));
dc.TextOut(0,200,str);
}
CView::OnTimer(nIDEvent);
}