MFC文本编程:创建插入符

一、创建文本插入符

Step01、创建插入符

相关函数/结构体
            CWnd::CreateSolidCaret(); 
             定义:void CreateSolidCaret(int nWidth,int nHeight);
        在View类中加入WM_CREATE消息的响应函数OnCreate,加入CreateSolidCaret()
        效果:没有显示插入符呀!   

QUOTE FROM MSDN
The CreateSolidCaret method automatically destroys the previous caret shape, if any, regardless of which window owns the caret. Once created, the caret is initially hidden. To show the caret, the ShowCaret method must be called.

Step02、显示插入符

        加上ShowCaret();
    Step03、让插入符跟字体大小相关
        相关函数/结构体:
            获取字符信息CDC::GetTextMetrics
            字符属性结构体TEXTMETRIC Structure

code
    ///////////////////////////////////////////////////////////////////////////// 
   
// CTextView message handlers 

   
int CTextView::OnCreate(LPCREATESTRUCT lpCreateStruct) 
    { 
       
if (CView::OnCreate(lpCreateStruct) == -1
           
return -1
       
//创建设备描述表 
        CClientDC dc(this); 
       
//定义文本信息结构体变量 
        TEXTMETRIC tm; 
       
//获得设备描述表中的文本信息 
        dc.GetTextMetrics(
&tm); 
       
//根据字体大小,创建合适的插入符 
        CreateSolidCaret(tm.tmAveCharWidth
/8, tm.tmHeight); 
       
//显示插入符 

        ShowCaret(); 
        SetTimer(
1,100,NULL); 
       
return 0
    } 

 

二、创建图形插入符

Step01、创建Bitmap


        定义:CBitmap bitmap;要放在View类的头文件中,并将其访问权限设置为private。为什么private?因为只在View类中调用。 

QUOTE
若将CBitmap bitmap放在CTextView中,bitmap为局部变量,当OnCreate()执行完毕会发生析构,相关的资源也会被销毁。那么说那幅位图也被销毁?应该不会吧?

Step02、创建图形插入符

  
        相关函数
            CWnd::CreateCaret();
                定义:void CreateCaret(CBitmap* pBitmap);                

Quote from MSDN
The bitmap must have previously been created by the CBitmap::CreateBitmap member function, the CreateDIBitmap Windows function, or the CBitmap::LoadBitmap member function.

所以需要Step01中把bitmap定义为全局变量。

OnCreate消息响应函数源代码
1    
2     /////////////////////////////////////////////////////////////////////////////
3     // CTextView message handlers
4     int CTextView::OnCreate(LPCREATESTRUCT lpCreateStruct) 
5     { 
6         if (CView::OnCreate(lpCreateStruct) == -1
7             return -1
8         bitmap.LoadBitmap(IDB_BITMAP1); 
9         CreateCaret(&bitmap); 
10         ShowCaret(); 
11         SetTimer(1,100,NULL); 
12         return 0
13     }
posted @ 2010-01-25 23:22  Anthony Lee  阅读(757)  评论(0编辑  收藏  举报