注意:光标这个中文经常被混用,其实光标的英文是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();//
}