目标:在笔记三的基础上,设定文字开始位置
一、建立单文档的工程,取名mouse,其他同笔记三
二、增加两个变量记录文字显示开始的位置
class CMouseView : public CView
{
protected: // create from serialization only
CMouseView();
DECLARE_DYNCREATE(CMouseView)
boolean Flag;//插入点是否建立的标志
CPoint CaretPosition;//插入点位置
int x,y;//记录文字显示开始的位置
// Attributes
x,y也需要在构造函数中初始化
CMouseView::CMouseView()
{
// TODO: add construction code here
Flag=false;//一开头为false,伧建后为true,只伧建一次Caret
x=y=0;
}
三、建立鼠标左键的消息处理程序
void CMouseView::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
x=point.x;
y=point.y;
CMouseDoc * p=GetDocument();
ASSERT_VALID(p);
p->StringData.Empty();//清空字符串
Invalidate();
CView::OnLButtonDown(nFlags, point);
}
四、修改OnDraw函数
1、textout函数要用x,y代替0,0;2、caret的位置计算要考虑x,y
void CMouseView::OnDraw(CDC* pDC)
{
CMouseDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
// TODO: add draw code for native data here
if (!Flag)//没有伧建过Caret则伧建
{
TEXTMETRIC textmetric;//The TEXTMETRIC structure contains basic information about a physical font.
pDC->GetTextMetrics(&textmetric);//The GetTextMetrics function fills the specified buffer with the metrics for the currently selected font.
CreateSolidCaret(textmetric.tmAveCharWidth/8,textmetric.tmHeight);//Creates a solid rectangle for the system caret and claims ownership of the caret.
//The caret shape can be a line or block.
//插入点高度为tmHeight,宽度则为tmAveCharWidth的1/8
CaretPosition.x=CaretPosition.y=0;//位置为0,因为一开头没有输入文字,也就没有文字显示
SetCaretPos(CaretPosition);//Sets the position of the caret.
ShowCaret();//Shows the caret on the screen at the caret’s current position.
Flag=true;//标记做好了,以后不再伧建
}
HideCaret();//
pDC->TextOut(x,y,pDoc->StringData);//输出字符串StringData
CSize charsize=pDC->GetTextExtent(pDoc->StringData);//计算尺寸,注意是两个方向的!
CaretPosition.x=x+charsize.cx;//
CaretPosition.y=y;
SetCaretPos(CaretPosition);//
ShowCaret();//
}