MFC学习笔记四 用鼠标设定文字显示开始位置

目标:在笔记三的基础上,设定文字开始位置

一、建立单文档的工程,取名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();//  
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值