MFC学习笔记三 加入插入点光标(Caret)

注意:光标这个中文经常被混用,其实光标的英文是cursor,是指鼠标的位置。而这里说的是插入点,英文是caret,是表示键入的字符放在哪个位置。

目标:在上一个程序中加入caret表示当前字符的位置。

一、建立一个MFC的单文档程序项目,取名Caret,其他同笔记二,实现显示键入的字符。

二、建立两个变量保存caret建立与否的标志和caret位置

从逻辑上看,这个是只与显示有关的,所以应该建立在视图而不是文档中。

类CCaretView定义中(caretView.h)写代码:

class CCaretView : public CView
{
protected: // create from serialization only
	CCaretView();
	DECLARE_DYNCREATE(CCaretView)
	boolean Flag;//插入点是否建立的标志
	CPoint CaretPosition;//插入点位置
// Attributes
public:
	CCaretDoc* GetDocument();

// Operations

类CCaretView构造函数中(caretView.cpp)初始化Flag( CaretPosition不需要在这里初始化):

CCaretView::CCaretView()
{
	// TODO: add construction code here
	Flag=false;//一开头为false,伧建后为true,只伧建一次Caret

}
三、处理caret

在OnDraw函数中写代码

void CCaretView::OnDraw(CDC* pDC)
{
	CCaretDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	// 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(0,0,pDoc->StringData);//输出字符串StringData
	CSize charsize=pDC->GetTextExtent(pDoc->StringData);//计算尺寸,注意是两个方向的!
	CaretPosition.x=charsize.cx;//
	SetCaretPos(CaretPosition);//
	ShowCaret();//
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值