StickysoftDESIGNS
Skip Navigation Links : Articles : WTL : Serialization support to CRichEditCtrl class

How to add a serialization support to CRichEditCtrl class

WTL comes with many control classes that provide standard elements of the user interface. One of them is CRichEditCtrl - a rich edit control that understands some basic RTF formatting and allows multiple fonts, colors, and so on. But some useful features that it's MFC counterpart has are missing in the WTL implementation, one of them being able to serialize CRichEditCtrl.

So I wrote a small class CRichEditEx that adds a serialization support to CRichEditCtrl class. This class is using CXArchive class also developed by me and, basically, a port of MFC code.

The demo project contains the CRichEditEx, CXArchive, CXFile classes implementations and example how to use them.
Selecting File->Save will store the contents of the rich edit control into the file and File->Open will insert text into the rich edit control.

How to use it

1. Derive your class from CRichEditEx like so:

class CRichEditDemoView : public CRichEditEx<CRichEditDemoView>
{
 ...
};
    

2. Add CXFile and CXArchive classes to your project:

#include "File.h";
#include "Archive.h";
    

3. Somewhere in your code where you want to save the contents of the rich edit control add the following code:

LRESULT OnFileSave(WORD, WORD, HWND, BOOL&)
{
    string strFile = "demo.txt";
  
    try
    {
        CXFile file;
        file.Open(strFile,       
            GENERIC_WRITE | GENERIC_READ,   
            FILE_SHARE_READ | FILE_SHARE_WRITE,  
            NULL,         
            CREATE_ALWAYS,       
            FILE_ATTRIBUTE_NORMAL,     
            NULL);         
   
        CXArchive ar(&file, CXArchive::store);
   
        m_view.Serialize(ar);
   
        ar.Close();
    }
    catch (CXException& Ex)
    {
        MessageBox(Ex.GetErrorDesc().c_str(), _T("Richedit Demo"), MB_OK);
    }
    catch (...)
    {
        MessageBox(_T("Unexpected error"), _T("Richedit Demo"), MB_OK);
    }

    return 0;
}
    

4. Somewhere in your code where you want to load the contents of the rich edit control from the file add the following code:

LRESULT OnFileOpen(WORD, WORD, HWND, BOOL&)
{
    string strFile = "demo.txt";

    try
    {
        CXFile file;
        file.Open(strFile,       
            GENERIC_WRITE | GENERIC_READ,    
            FILE_SHARE_READ | FILE_SHARE_WRITE,  
            NULL,         
            OPEN_EXISTING,       
            FILE_ATTRIBUTE_NORMAL,     
            NULL);         
   
        CXArchive ar(&file, CXArchive::load);
   
        m_view.Serialize(ar);
   
        ar.Close();
    }
    catch (CXException& Ex)
    {
        MessageBox(Ex.GetErrorDesc().c_str(), _T("Richedit Demo"), MB_OK);
    }
    catch (...)
    {
        MessageBox(_T("Unexpected error"), _T("Richedit Demo"), MB_OK);
    }

    return 0;
}
    
Download the source code