[MFC] RichEdit 控件使用

本文详细介绍了在MFC中使用RichEdit控件的方法,包括如何加载控件、设置只读属性、判断光标状态、在编辑框中添加字符串、随输入自动滚动到最后一行、限制输入指定字符、使用Richedit2.0或Richedit3.0、改变指定区域的颜色及字体、设置行间距、插入位图、gif动画、OLE对象、使选中内容只读、打印RichEdit、用于聊天消息窗口、解决EN_SETFOCUS和EN_KILLFOCUS无响应的问题、拼写检查、改变编辑背景色等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在mfc中使用工具栏里的RichEdit 控件时,应该在程序初始话时加入AfxInitRichEdit,或者 AfxInitRichEdit2 
否则的话 程序会起不来.也没有任何错误信息.
这俩函数 是加载 Riched20.dll(Riched32.dll )的.

1.设置edit只读属性

    方法一:
                m_edit1.SetReadOnly(TRUE);
    方法二:
                ::SendMessage(m_edit1.m_hWnd, EM_SETREADONLY, TRUE, 0);


2.判断edit中光标状态并得到选中内容(richedit同样适用)

        int nStart, nEnd;
        CString strTemp;

        m_edit1.GetSel(nStart, nEnd);
        if(nStart == nEnd)
        {
            strTemp.Format(_T("光标在%d"), nStart);
            AfxMessageBox(strTemp);
        }
        else
        {
            //得到edit选中的内容     
            m_edit1.GetWindowText(strTemp);
            strTemp = strTemp.Mid(nStart) - strTemp.Mid(nEnd);
            AfxMessageBox(strTemp); 
        }
    注:GetSel后,如果nStart和nEnd,表明光标处于某个位置(直观来看就是光标在闪动);
             如果nStart和nEnd不相等,表明用户在edit中选中了一段内容。


3.在edit最后添加字符串

        CString str;
        m_edit1.SetSel(-1, -1);
        m_edit1.ReplaceSel(str);


4.随输入自动滚动到最后一行(richedit同样适用)

    方法一:(摘自msdn)
        // The pointer to my edit.
        extern CEdit* pmyEdit;
        int nFirstVisible = pmyEdit->GetFirstVisibleLine();

        // Scroll the edit control so that the first visible line
        // is the first line of text.
        if (nFirstVisible > 0)
        {
            pmyEdit->LineScroll(-nFirstVisible, 0);
        }
    方法二:
        m_richedit.PostMessage(WM_VSCROLL, SB_BOTTOM, 0);


5.如何限制edit输入指定字符

   可以从CEdit派生一个类,添加WM_CHAR消息映射。下面一个例子实现了限定输入16进制字符的功能。

   void CMyHexEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) 
   { 
        if ( (nChar >= '0' && nChar <= '9') || 
             (nChar >= 'a' && nChar <= 'f') || 
         (nChar >= 'A' && nChar <= 'F') || 
              nChar == VK_BACK || 
              nChar == VK_DELETE)    //msdn的virtual key
       { 
            CEdit::OnChar(nChar, nRepCnt, nFlags); 
        }    
   }


6.如何使用richedit

    添加AfxInitRichEdit();
       CxxxApp::InitInstance()
        {
             AfxInitRichEdit();
          .............
       }

   AfxInitRichEdit()功能:装载 RichEdit 1.0 Control (RICHED32.DLL).


7.如何使用richedit2.0 or richedit3.0

    使用原因:由于RichEdit2.0A自动为宽字符(WideChar),所以它可以解决中文乱码以及一些汉字问题

    方法一:(msdn上的做法,适用于用VC.NET及以后版本创建的工程)
            To update rich edit controls in existing Visual C++ applications to version 2.0,
            open the .RC file as text, change the class name of each rich edit control from   "RICHEDIT" to "RichEdit20a". 
            Then replace the call to AfxInitRichEdit with AfxInitRichEdit2.
    方法二:以对话框为例:
       (1)    增加一全局变量 HMODULE hMod;
       (2)    在CxxxApp::InitInstance()中添加一句hMod = LoadLibrary(_T("riched20.dll"));
            在CxxxApp::ExitInstance()中添加一句FreeLibrary(hMod);
       (3)    在对话框上放一个richedit,文本方式打开.rc文件修改该richedit控件的类名"RICHEDIT" to "RichEdit20a".
       (4)    在对话框头文件添加 CRichEditCtrl m_richedit;
            在OnInitDialog中添加 m_richedit.SubclassDlgItem(IDC_RICHEDIT1, this);


8.改变richedit指定区域的颜色及字体

        CHARFORMAT cf;
        ZeroMemory(&cf, sizeof(CHARFORMAT));
        cf.cbSize = sizeof(CHARFORMAT);
        cf.dwMask = CFM_BOLD | CFM_COLOR | CFM_FACE |
                            CFM_ITALIC | CFM_SIZE | CFM_UNDERLINE;
        cf.dwEffects = 0;
        cf.yHeight = 12*12;//文字高度
        cf.crTextColor = RGB(200, 100, 255); //文字颜色
        strcpy(cf.szFaceName ,_T("隶书"));//设置字体
     
        m_richedit1.SetSel(1, 5); //设置处理区域
        m_richedit1.SetSelectionCharFormat(cf);


9.设置行间距(只适用于richedit2.0)

        PARAFORMAT2 pf;
        pf2.cbSize = sizeof(PARAFORMAT2);
        pf2.dwMask = PFM_LINESPACING | PFM_SPACEAFTER;
        pf2.dyLineSpacing = 200;
        pf2.bLineSpacingRule = 4;
        m_richedit.SetParaFormat(pf2);


10.richedit插入位图

Q220844:How to insert a bitmap into an RTF document using the RichEdit control in Visual C++ 6.0
http://support.microsoft.com/default.aspx?scid=kb;en-us;220844
http://www.codeguru.com/Cpp/controls/richedit/article.php/c2417/
http://www.codeguru.com/Cpp/controls/richedit/article.php/c5383/


11.richedit插入gif动画

http://www.codeproject.com/richedit/AnimatedEmoticon.asp


12.richedit嵌入ole对象

http://support.microsoft.com/kb/141549/en-us


13.使richedit选中内容只读

http://www.codeguru.com/cpp/controls/richedit/article.php/c2401/


14.打印richedit

http://www.protext.com/MFC/RichEdit3.htm


15.richeidt用于聊天消息窗口

http://www.vckbase.com/document/viewdoc/?id=1087
http://www.codeproject.com/richedit/chatrichedit.asp
http://www.codeguru.com/Cpp/controls/richedit/article.php/c2395/


16.解决richedit的EN_SETFOCUS和EN_KILLFOCUS无响应的问题

http://support.microsoft.com/kb/181664/en-us


17.richedit拼写检查

http://www.codeproject.com/com/AutoSpellCheck.asp


18.改变edit背景色

Q117778:How to change the background color of an MFC edit control
http://support.microsoft.com/kb/117778/en-us


19.当edit控件的父窗口属性是带标题栏WS_CAPTION和子窗口WS_CHILD时,不能设置焦点SetFocus

Q230587:PRB: Can't Set Focus to an Edit Control When its Parent Is an Inactive Captioned Child Window
http://support.microsoft.com/kb/230587/en-us


20. 在Edit中回车时,会退出对话框 

选中Edit的风格Want Return。

MSDN的解释如下:
ES_WANTRETURN    Specifies that a carriage return be inserted when the user presses the ENTER key while entering text into a multiple-line edit control in a dialog box. Without this style, pressing the ENTER key has the same effect as pressing the dialog box's default pushbutton. This style has no effect on a single-line edit control.


21. 动态创建的edit没有边框的问题

    m_edit.Create(....);
    m_edit.ModifyStyleEx(0, WS_EX_CLIENTEDGE, SWP_DRAWFRAME);


22. 一个能显示RTF,ole(包括gif, wmv,excel ,ppt)的例子

http://www.codeproject.com/richedit/COleRichEditCtrl.asp

转自

http://blog.csdn.net/lixiaosan/archive/2006/04/06/652795.aspx

Environment: VC6 SP4, 2000.

Follow these 10 easy steps to build the OutLookRichEdit control:

  1. Insert a rich edit control into the dialog.
  2. Call AfxInitRichEdit() in the InitInstance of the App class or in InitDialog.
  3. If it does not exist, copy OutLookRichEdit.cpp and OutLookRichEdit.h to the project directory.
  4. Click the menu choice Project-Add to Project-Files and select the above-copied files to add the wrapper class to your project.
  5. Import the hand cursor into the resource and rename it "IDC_LINK".
  6. Use Classwizard to add a member variable of the rich edit control (CRichEditCtrl).
  7. Include the OutLookRichEdit.h file in the dialog's header file and change the declaration of rich edit member variable, as in
    CRichEditCtrl    m_ctrlText1;
    to
    COutLookRichEdit m_ctrlText1;
  8. In InitDialog(), add the following code.
    m_ctrlText1.SetRawHyperText(_T("Click <%$here$#100#%>
                                    to see the about box."));

    At this level, if you build the project and run it, you can see the rich edit control with linked text, but nothing would happen if you clicked on the link.

    To Show a dialog while the link is clicked, you have to add some more code in the dialog class. Before that, have a closer look at the preceding code and hypertext syntax. The link text is enclosed between the "$" symbols and the corresponding dialog's resource value 100 (About Box), enclosed in "#" symbols.

    You can find the #define values of dialogs in the resource.h file.

  9. Use ClassWizard to map OnNotify of the dialog and write the corresponding implementation code in .cpp file, like:
    BOOL CDEMODlg::OnNotify(WPARAM wParam,
                            LPARAM lParam,
                            LRESULT* pResult)
    {
      NMHDR* pNmHdr = (NMHDR*) lParam;
      if(IDC_RICHEDIT1 == pNmHdr->idFrom){
        switch(pNmHdr->code)
        {
          case IDD_ABOUTBOX:
            CAboutDlg oDlg;
            oDlg.DoModal ();
            break;
        }
      }
      return CDialog::OnNotify(wParam, lParam, pResult);
    }
  10. Now, build and run the project. It is recommended that you set the read-only attribute to the rich edit control.

Downloads

Download demo project - 23 Kb
Download source - 6 Kb

在RichEdit中插入Bitmap

COleDataSource src;
STGMEDIUM sm;
sm.tymed=TYMED_GDI;
sm.hBitmap=hbmp;
sm.pUnkForRelease=NULL;
src.CacheData(CF_BITMAP, &sm);
LPDATAOBJECT lpDataObject =
(LPDATAOBJECT)src.GetInterface(&IID_IDataObject);
pRichEditOle->ImportDataObject(lpDataObject, 0, NULL);
lpDataObject->Release();

字体设置代码

最后添加字体变换函数: 
CHARFORMAT cf; 
LOGFONT lf; 
memset(&cf, 0, sizeof(CHARFORMAT)); 
memset(&lf, 0, sizeof(LOGFONT)); 

//判断是否选择了内容 
BOOL bSelect = (GetSelectionType() != SEL_EMPTY) ? TRUE : FALSE; 
if (bSelect) 

             GetSelectionCharFormat(cf); 

else 

             GetDefaultCharFormat(cf); 


//得到相关字体属性 
BOOL bIsBold = cf.dwEffects & CFE_BOLD; 
BOOL bIsItalic = cf.dwEffects & CFE_ITALIC; 
BOOL bIsUnderline = cf.dwEffects & CFE_UNDERLINE; 
BOOL bIsStrickout = cf.dwEffects & CFE_STRIKEOUT; 

//设置属性 
lf.lfCharSet = cf.bCharSet; 
lf.lfHeight = cf.yHeight/15; 
lf.lfPitchAndFamily = cf.bPitchAndFamily; 
lf.lfItalic = bIsItalic; 
lf.lfWeight = (bIsBold ? FW_BOLD : FW_NORMAL); 
lf.lfUnderline = bIsUnderline; 
lf.lfStrikeOut = bIsStrickout; 
sprintf(lf.lfFaceName, cf.szFaceName); 
             

CFontDialog dlg(&lf); 
dlg.m_cf.rgbColors = cf.crTextColor; 
if (dlg.DoModal() == IDOK) 

             dlg.GetCharFormat(cf);//获得所选字体的属性 
             if (bSelect) 
                         SetSelectionCharFormat(cf);     //为选定的内容设定所选字体 
             else 
                         SetWordCharFormat(cf);         //为将要输入的内容设定字体 
}

在RichEdit中实现超链接

在RichEdit中实现超链接
责任编辑:admin   在CBuilder上制作 更新日期:2005-8-6
 
首先在Form上放置一个RichEdit。

在窗体的构造函数中添加以下代码:
__fastcall TMainForm::TMainForm(TComponent* Owner)
         : TForm(Owner)
{
     unsigned mask = SendMessage(RichEdit1->Handle, EM_GETEVENTMASK, 0, 0);
     SendMessage(RichEdit1->Handle, EM_SETEVENTMASK, 0, mask | ENM_LINK);
     SendMessage(RichEdit1->Handle, EM_AUTOURLDETECT, true, 0);   //自动检测URL

     RichEdit1->Text = "欢迎访问C++ Builder\n"
                       "网址: http://www.ccrun.com\n"
                       "偶的信箱:\n"
                       "mailto::info@ccrun.com \n"
                       "嘿嘿\n";
}

重载窗体的WndProc

1。在.h中添加:

    protected:
       virtual void __fastcall WndProc(Messages::TMessage &Message);

2。在.cpp中添加:
//---------------------------------------------------------------------------
void __fastcall TMainForm::WndProc(Messages::TMessage &Message)
{
     if (Message.Msg == WM_NOTIFY)
     {
         if (((LPNMHDR)Message.LParam)->code == EN_LINK)
         {
             ENLINK* p = (ENLINK *)Message.LParam;
             if (p->msg == WM_LBUTTONDOWN)
             {
                 SendMessage(RichEdit1->Handle, EM_EXSETSEL, 0, (LPARAM)&(p->chrg));
                 ShellExecute(Handle, "open", RichEdit1->SelText.c_str(), 0, 0, SW_SHOWNORMAL);
             }
         }
     }
     TForm::WndProc(Message);
}
<think>好的,我现在需要帮助用户解决在MFCRichEdit控件中插入OLE对象的问题。首先,我需要回忆一下MFCRichEdit控件的相关知识。用户可能想要通过代码示例了解具体的实现步骤,所以我得先确保自己理解相关的类和函数。 首先,插入OLE对象通常涉及到CRichEditCtrl类。我记得CRichEditCtrl有几个成员函数,比如InsertObject,可能用于插入OLE对象。另外,可能还需要使用OLE相关的结构,比如REOBJECT,来配置对象属性。 接下来,我需要考虑如何初始化OLE库。因为在使用OLE功能之前,必须调用AfxOleInit()来初始化,这一步很重要,否则程序可能会崩溃或者功能无法正常使用。所以在示例代码中,应该提醒用户在应用程序初始化时调用这个函数。 然后,创建RichEdit控件。用户可能已经知道如何创建控件,但为了完整性,还是需要提到使用CRichEditCtrl::Create函数,并设置适当的样式,比如加上AFX_IDW_PANE_FIRST作为子窗口ID,以及设置WS_VISIBLE和WS_CHILD等窗口样式。 关于插入OLE对象的步骤,可能需要先准备一个OLE客户端项,比如从COleClientItem派生一个类。然后,使用CRichEditCtrl::InsertObject函数插入该对象。需要填充REOBJECT结构体,指定对象的类、显示方式等属性。例如,clsid可能设置为CLSID_NULL,或者具体的OLE对象类型,比如Excel工作表或Word文档。 还需要考虑用户如何激活或编辑插入的OLE对象。RichEdit控件通常支持双击对象进行编辑,这可能涉及到处理鼠标消息或者使用特定的成员函数,比如DoVerb,来触发对象的动作。 此外,可能还需要处理OLE对象的持久化存储,比如使用序列化将对象保存到文件或从文件加载。这涉及到重写COleClientItem的Serialize函数,以及确保文档类正确管理这些OLE项。 在编写示例代码时,应该分步骤说明,比如初始化OLE、创建控件、插入对象的具体代码,并解释每个参数的作用。同时,要提醒用户注意资源管理和错误处理,比如检查OLE初始化是否成功,对象是否创建成功等。 可能遇到的问题包括OLE初始化失败,对象无法插入,或者插入后无法激活。这时候需要检查返回值和可能的错误代码,使用TRACE宏输出调试信息有助于发现问题。 最后,用户可能还需要知道如何验证OLE对象是否插入成功,比如运行程序后查看控件中是否有对象显示,双击是否能打开相应的应用程序进行编辑。这部分可以作为验证步骤加入到教程中。 总结一下,我需要提供一个清晰的步骤指南,包括代码示例和关键点解释,确保用户能够按照步骤实现插入OLE对象的功能,并理解背后的原理和注意事项。同时,根据用户提供的引用资料,特别是引用[4]提到嵌入和链接的选择,可能需要简要说明两者区别,并在示例中展示如何选择嵌入方式。</think>在MFC的`CRichEditCtrl`控件中插入OLE对象需要以下关键步骤: ### 1. OLE初始化 在应用程序类`CWinApp::InitInstance()`中初始化OLE库: ```cpp if (!AfxOleInit()) { AfxMessageBox(_T("OLE初始化失败")); return FALSE; } ``` 此步骤确保OLE功能可用[^4]。 ### 2. 创建RichEdit控件 在对话框或窗口类中创建控件: ```cpp m_richEdit.Create( WS_VISIBLE | WS_CHILD | ES_MULTILINE | ES_AUTOVSCROLL, CRect(10, 10, 300, 200), this, AFX_IDW_PANE_FIRST); ``` ### 3. 插入OLE对象 使用`InsertObject`方法插入对象: ```cpp // 创建OLE客户端项 COleClientItem* pItem = new COleClientItem(); if (pItem->CreateNewObject(__uuidof(Word.Document))) { // 配置对象属性 REOBJECT reobj = {0}; reobj.cbStruct = sizeof(REOBJECT); reobj.cp = REO_CP_SELECTION; reobj.clsid = pItem->GetType(); reobj.poleobj = pItem->GetInPlaceObject(); // 插入到RichEdit控件 m_richEdit.InsertObject(&reobj); } ``` 此代码示例插入一个Word文档对象,支持双击激活编辑。 ### 完整示例流程 ```cpp // 对话框类头文件声明 CRichEditCtrl m_richEdit; // 对话框初始化代码 BOOL CMyDialog::OnInitDialog() { CDialog::OnInitDialog(); // 创建RichEdit控件 m_richEdit.Create(..., this, IDC_RICHEDIT); // 插入OLE对象 InsertOleObject(); return TRUE; } void CMyDialog::InsertOleObject() { // OLE项创建逻辑如步骤3所示 } ``` ### 关键特性说明 1. **对象激活**:用户双击对象自动触发关联程序 2. **数据持久化**:需实现序列化保存OLE内容 3. **对象类型**:支持所有注册的OLE服务器(Excel/Word/自定义对象)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值