RichEditCtrl experience

RichEditCtrl experience

1. Common problems 
a.
AfxInitRichEdit() that can be compiled but cannot be executed  ; 
b. Upgrade the default Riched version (the default has some bugs), such as 
adding
LoadLibrary(" RICHED20.DLL ")  in InitInstance, and 
finally pay attention to FreeLibrary if it is Available
BOOL of the CRichEditView base class  CXXXXXXView::PreCreateWindow(CREATESTRUCT& cs) 

//Load rich edit version 2.0 
if (LoadLibraryA("RICHED20.DLL") == NULL) 

AfxMessageBox(_T("Fail to load/"riched20. dll/"."),MB_OK | MB_ICONERROR); 
PostMessage(WM_QUIT,0,0); 
return FALSE; 
} m_strClass = RICHEDIT_CLASSA;//for 2.0 class return CRichEditView::PreCreateWindow(cs); 

c. Finally, add the line 
richeditctrl .SetSel(-1, -1); 
richeditctrl.ReplaceSel( (LPCTSTR)str ); 
d. Word limit 
CRichEditCtrl::LimitText(long nChars) 
e. New line switch 
CRichEditView's OnInitialUpdate() function add the following two sentences: 
m_nWordWrap = WrapNone; 
WrapChanged(); 
WrapChanged is actually the same Call 
ctrl.SetTargetDevice(NULL, 1);//m_nWordWrap == WrapNone 
ctrl.SetTargetDevice(NULL, 0);//m_nWordWrap == WrapToWindow 
and the less commonly used m_nWordWrap == WrapToTargetDevice 
ctrl.SetTargetDevice(m_dcTarget, GetPrintWidth()) ; 
If the Dialog may be used SetTargetDevice, under properties noted plus want return f sometimes undesirable data pasted with the format, can be selectively attached by PasteSpecial. 
pmyRichEditCtrl ->; PasteSpecial (the CF_TEXT); 
. with G Enter to scroll to the last line with the automatic scroll bar 
int nFirstVisible = pmyRichEditCtrl->GetFirstVisibleLine(); 
if (nFirstVisible> 0) 

pmyRichEditCtrl->LineScroll(-nFirstVisible, 0); 

or 
m_cRichEdit.PostMessage(WM_VSCROLL, SB_BOTTOM,0); 
h. Set the number of UNDO (can only be used above RICHED20, that is, it is not supported by default, Must be upgraded) 
SendMessage(EM_SETTEXTMODE,TM_MULTILEVELUNDO,0); 
TM_MULTILEVELUNDO supports multiple cancellation (default value). The maximum number of times can be set by EM_SETUNDOLIMIT 
SendMessage(EM_SETUNDOLIMIT,100,0); i. Response OnChange 
EM_SETEVENTMASK set ENM_GEEvent 
long lMask = Get; 
lMask |= ENM_CHANGE; 
lMask &= ~ENM_PROTECTED; 
SetEventMask(lMask); j. Set read-only 
CRichEditCtrl::SetReadOnly( BOOL bReadOnly = TRUE ); 
Realize the selected text read-only by setting PROTECTED, see 
www.codeguru.com/Cpp/control...2  
. Function application 
a. Set the font (mainly through SetSelectionCharFormat) 
CHARFORMAT cf; 
ZeroMemory(&cf, sizeof(CHARFORMAT)); 
cf.cbSize = sizeof(CHARFORMAT); 
cf.dwMask|=CFM_BOLD; 
cf.dwEffects|=CFE_BOLD;//Set bold body, & = ~ cancel member and the CFE_AUTOCOLOR with cf.dwEffects; 
cf.dwMask | = CFM_ITALIC; 
cf.dwEffects | = CFM_PROTECTED The CFE_PROTECTED;//set in italics, with the canceled = ~ & CFM_PROTECTED The CFE_PROTECTED cf.dwEffects; 
cf.dwMask | = CFM_UNDERLINE; 
cf.dwEffects | =CFE_UNDERLINE;//Set italics, cancel cf.dwEffects&=~CFE_UNDERLINE; 
cf.dwMask|=CFM_COLOR; 
cf.crTextColor = RGB(255,0,0);//Set color 
cf.dwMask|=CFM_SIZE; 
cf. yHeight =200;//Set the height 
cf.dwMask|=CFM_FACE; 
strcpy(cf.szFaceName ,_T("Chapter"));//Set the font 
rich.SetSelectionCharFormat(cf); 
b. Set the line spacing of the font 
To use richedit2.0 and above to 
try 
PARAFORMAT2 pf; 
pf.cbSize = sizeof(PARAFORMAT2); 
pf.dwMask = PFM_NUMBERING | PFM_OFFSET; 
pf.wNumbering = PFN_BULLET;//Note PFM_NUMBERING 
pf.dxOffset = 10; 
VERIFY(SetParaFormat(pf) ); The 
commonly used dwMask has the 
PFM_NUMBERING member wNumbering to work, bullets, the default is PFN_BULLET 
2 Use Arabic numerals (1, 2, 3, ...).   
3 Use lowercase letters (a, b, c, ...) .   
4 Use uppercase letters (A, B, C, ...).   
5 Use lowercase Roman numerals (i, ii, iii, ...).   
6 Use uppercase Roman numerals (I, II, III, ...) .   
7 Custom, see member wNumberingStart for characters.   
PFM_OFFSET member dxOffset only works, indentation, unit twips 
PFM_STARTINDENT member dxStartIndent only works, first line indentation 
PFM_SPACEAFTER member dySpaceAfter works, paragraph spacing 
PFM_LINESPACING member dyLineSpacing works, line spacing 
c. Set CRichEditCtrl(2.0) background transparency 
long style = ::GetWindowLong(GetSafeHwnd(), GWL_EXSTYLE); 
style &= WS_EX_TRANSPARENT; 
::SetWindowLong(GetSafeHwnd(), GWL_EXSTYLE, style); 
Or CreateEx, and then add the WS_EX_TRANSPARENT style to e. There are three types of content 
1) GetWindowText 
2) Use EM_GETTEXTEX 
GETTEXTEX gt; 
gt.cb = 200; 
gt.flags = GT_DEFAULT; 
gt.codepage = CP_ACP; 
gt.lpDefaultChar = NULL; 
gt .lpUsedDefChar = NULL; 
SendMessage(EM_GETTEXTEX,(WPARAM)>,(LPARAM)text); 
3)StreamOut (mainly used for RTF and other format output) 
static DWORD CALLBACK 
MyStreamOutCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb) 

CFile * pFile = (CFile*) dwCookie; pFile->Write(pbBuff, cb); 
*pcb = cb; return 0; 

CFile cFile(TEXT("myfile.rtf"), CFile::modeCreate|CFile::modeWrite ); 
EDITSTREAM es; 
es.dwCookie = (DWORD) &cFile;//Set the use case parameters so that the callback function can call 
es.pfnCallback = MyStreamOutCallback; 
pmyRichEditCtrl->StreamOut(SF_RTF, es); The
reading can be analogized  , SetWindowText, EM_SETTEXTEX, StreamIn f. Find the string 
FINDTEXTEX ft; 
ft.chrg.cpMin = 0; 
ft.chrg.cpMax = -1; 
ft.lpstrText = "|"; 
long lPos = FindText(0, &ft); If you want to continue the search, modify cpMin, such as 
int nCount = 0; 
do 

long lPos = GetRichEditCtrl().FindText(0, &ft); 
if( -1 == lPos) break; 
ft.chrg.cpMin = lPos + strlen(ft.lpstrText); 
++nCount; 
}while(TRUE); g. Save the
current practice in Html  format, you can first convert to RTF format, and then use RTF-to-HTML Converter 
www. codeguru.com/Cpp/control... 
h. Overload the OnProtected function to get the corresponding message, such as paste, etc. 
void CMYichEditorView::OnProtected(NMHDR* pNMHDR, LRESULT* pResult) 

ENPROTECTED* pEP = (ENPROTECTED*)pNMHDR; switch (pEP ->msg) { 
case WM_KEYDOWN://key, judge pEP->wParam 
case WM_PASTE://paste 
case WM_CUT://cut 
case EM_SETCHARFORMAT: 
default: 
break; 
}; 
*pResult = FALSE; 

3. Frequently used chat 
a .LINK link function 
1. LoadLibrary(_T("Riched20.dll")); 
2. Create RichEdit2.0 control 
CreateEx(0, _T("RichEdit20A"), NULL, WS_CHILD|WS_VISIBLE|WS_VSCROLL|WS_TABSTOP 
|ES_READONLY|ES_WANTRETURN|ES_MULTILINE, 
rect.left, rect.top, cx, cy, 
pParentWnd->m_hWnd, NULL) ); 
3. Set the selected text as a link display 
CHARFORMAT2 cf2; 
ZeroMemory(&cf2, sizeof(CHARFORMAT2));// 
cf2.cbSize = sizeof(CHARFORMAT2); 
cf2.dwMask = CFM_LINK; 
cf2.dwEffects |= CFE_LINK; 
m_cRichEdit .SendMessage (EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) & CF2); 
4. click the support link in response 
m_cRichEdit.SetEventMask (ENM_LINK); 
5. the response clicks on links BEGIN_MESSAGE_MAP EN_LINK (CMyRichEdit, CRichEditCtrl) 
ON_NOTIFY_REFLECT. (EN_LINK, OnURL) 
END_MESSAGE_MAP () 
...... void CMyRichEdit::OnURLClick(NMHDR *pNmhdr, LRESULT *pResult) 

TCHAR LinkChar[512]; 
ENLINK *pLink = (ENLINK *)pNmhdr; 
if (pLink->msg == WM_LBUTTONUP) 

SetSel( penLink->chrg);//This is the text range of the link 
long Res = GetSelText((char *)LinkChar);//This is the link text
//Following  is your processing 
... 

} b. Insert bitmap 
www.codeguru.com/Cpp/control...  
www.codeguru.com/Cpp/control... 
Customize the icon of the object inserted in RichEdit 
www.blogcn.com/user3/jiang... The 
method is basically the same as the Knowledge Base article Q220844 HOWTO : Insert a Bitmap Into an RTF Document Using the RichEdit Control 
Just call IOleCache::SetData before the last insertion, and use a HGLOBAL as a parameter. The data in HGLOBAL is a METAFILEPICT structure. You can insert the image using CRichEditView::InsertFileAsObject including the picture you provided. VC++ comes with an example WordPad. 
You can also refer to "Insert any HBITMAP (Bitmap) in your RichEdit Control" ( www.codeguru.com/richedit/ri... ). 
c. The
most common way to display GIF animation  is through qq's imageole.dll (also useful Gif89.dll) 
www.xiaozhou.net/cooldog/blo...  
www.codeproject.com/richedit/An 
... insert dynamic GIF ( Native C++ version) 
blog.joycode.com/jiangsheng/... 
d. Use of IRichEditOleCallback 
http://61.186.252.131/Expert/topic/905/905844.xml?temp=.8379022 
Similar to the production of MSN message sending box (on) 
www.vckbase.com/document/vi...The 
content includes: implement right-click menu, insert picture, read/write RTF format string, custom CRichEditCtrl control 
www.vckbase.com/document/vi... 
The content includes: right mouse button message, message mapping, font change. After the PS.richedit control is upgraded to 2.0, first set the font to KaiTi. There is no problem in entering Chinese characters, but when entering letters, the letters automatically jump to Arial font, but 1.0 does not This title is still in italics to display the letters 
is a special design Dual-font, Smart font apply, see  http://61.186.252.131/Expert/topic/913/913807.xml?temp=.3753778

Note: 
m_edit1 represents the control type variable of the CEdit control whose ID is IDC_EDIT1 m_richedit1 represents the control type variable 
of the CRichEditCtrl control whose ID is IDC_RICHEDIT1 
---------------------- -------------------------------------------------- -------- 
1. Set the edit read-only attribute 
Method one: 
m_edit1.SetReadOnly(TRUE); 
Method two: 
::SendMessage(m_edit1.m_hWnd, EM_SETREADONLY, TRUE, 0); 
------- -------------------------------------------------- ----------------------- 
2. Determine the cursor status in edit and get the selected content (richedit is also applicable) 
int nStart, nEnd; 
CString strTemp; 
m_edit1.GetSel (nStart, nEnd); 
if(nStart == nEnd) 

strTemp.Format(_T("Cursor in%d"), nStart); 
AfxMessageBox(strTemp); 

else 

//Get the content selected by edit    
m_edit1.GetWindowText(strTemp); 
strTemp = strTemp.Mid(nStart)-strTemp.Mid(nEnd); 
AfxMessageBox(strTemp); 

Note: After GetSel, if nStart and nEnd are A position (intuitively, the cursor is flashing); 
if nStart and nEnd are not equal, it indicates that the user has selected a section of content in edit. 
-------------------------------------------------- ------------------------------ 
3. Add the string
CString str at the end of edit  ; 
m_edit1.SetSel(-1, -1 ); 
m_edit1.ReplaceSel(str); 
----------------------------------------- --------------------------------------- 
4. Automatically scroll to the last line with input (richedit The same applies) 
Method 1: (from 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); 

Method 2: 
m_richedit.PostMessage(WM_VSCROLL, SB_BOTTOM , 0); 
---------------------------------------------- ---------------------------------- 
5. How to restrict edit input specified characters 
can derive a class from CEdit, add WM_CHAR message mapping. The following example implements the function of restricting input hexadecimal characters. 
void CMyHexEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) 

if ((nChar >= '0' && nChar <= '9') || 
(nChar >='a' && nChar <='f') || 
(nChar >='A' && nChar <='F' 



CEdit::OnChar(nChar, nRepCnt, nFlags); 
}      

----------------------------------- --------------------------------------------- 
6. How to use richedit 
Add AfxInitRichEdit(); 
CxxxApp::InitInstance() 

AfxInitRichEdit(); 
............. 

AfxInitRichEdit() function: Load RichEdit 1.0 Control (RICHED32.DLL). 
----- -------------------------------------------------- ------------------------- 
7. How to use richedit2.0 or richedit3.0 
Reason for use: Because RichEdit2.0A is automatically a wide character (WideChar) , So it can solve Chinese garbled and some Chinese characters. 
Method 1: (The method on msdn is suitable for projects created with VC.NET and later versions) 
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 AfxInitRichEdit 
2. Method 2: Take the dialog box as an example: 
(1) Add a global Variable HMODULE hMod; 
(2) Add a sentence in CxxxApp::InitInstance() hMod = LoadLibrary(_T("riched20.dll")); 
Add a sentence in CxxxApp::ExitInstance() FreeLibrary(hMod); 
(3) In Put a richedit on the dialog box, open the .rc file in text mode and modify the class name of the richedit control "RICHEDIT" to "RichEdit20a". 
(4) Add CRichEditCtrl m_richedit
in the header file of the dialog box;  add m_richedit.SubclassDlgItem(IDC_RICHEDIT1, in OnInitDialog, this); 
----------------------------------------------- --------------------------------- 
8. Change the color and font of the area specified by 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/Text height 
cf.crTextColor = RGB(200, 100, 255);//Text color 
strcpy(cf.szFaceName ,_T("Chapter"));//Set the font 
m_richedit1.SetSel(1, 5);//Set Processing area 
m_richedit1.SetSelectionCharFormat(cf); 
----------------------------------------- --------------------------------------- 
9. Set line spacing (only applicable to 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 
insert a bitmap Q220844: How to insert a bitmap into an RTF document using the RichEdit control in Visual C++ 6.0 
support.microsoft.com/default.asp...  
www.codeguru.com/Cpp/control...  
www.codeguru.com/Cpp/control... 
-------- -------------------------------------------------- ---------------------- 
11.richedit inserts gif animation 
www.codeproject.com/richedit/An... 
------------ -------------------------------------------------- ------------------ 
12.richedit embeds ole object 
support.microsoft.com/kb/141549/e... 
-------------- -------------------------------------------------- ---------------- 
13. Make richedit selected content read-only 
www.codeguru.com/cpp/control... 
-------------------------------- ------------------------------------------------ 
14. Print richedit 
www.protext.com/MFC/RichEdi... 
-------------------------------------- ------------------------------------------ 
15.richeidt is used for chat message window 
www.vckbase.com/document/vi...  
www.codeproject.com/richedit/ch...  
www.codeguru.com/Cpp/control... 
-------------------- -------------------------------------------------- ---------- 
16. Solve the problem that the EN_SETFOCUS and EN_KILLFOCUS of richedit are not responding 
support.microsoft.com/kb/181664/e... 
---------------- -------------------------------------------------- -------------- 
17.richedit spell check 
www.codeproject.com/com/AutoSpe... 
---------------------------------------- ---------------------------------------- 
18. Change edit background color 
Q117778: How to change the background color of an MFC edit control 
support.microsoft.com/kb/117778/e  
----------------------------- -------------------------------------------------- - 
19. when the edit control's parent window with a title bar when the property is WS_CAPTION and child window WS_CHILD, can not set the focus SetFocus 
Q230587: PRB: focus to the set of can not control AN Edit the when the parent is is the ITS AN Inactive Captioned child window 
support.microsoft. com/kb/230587/e... 
------------------------------------------ -------------------------------------- 
20. When you press Enter in Edit, you will exit the dialog box 
select Edit style Want Return. 
MSDN's explanation is as follows: 
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, 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. The dynamically created edit does not The problem with the border 
m_edit.Create(....); 
m_edit.ModifyStyleEx(0, WS_EX_CLIENTEDGE, SWP_DRAWFRAME); 
-------------------------- -------------------------------------------------- ---- 
22. An example that can display RTF, ole (including gif, wmv, excel, ppt) 
www.codeproject.com/richedit/CO...

Reprinted: bbs.chinavideo.org/viewthread.

3. Some personal things (example)

Initialization: AfxInitRichEdit2();

The two RichEditCtrl in the window correspond:

CRichEditCtrl m_rtdRecv;//Receive window 
CRichEditCtrl m_rtdSend;//Send window

//Set richEdit window properties 
void CDemoDlgMsg::SetRichEditStyle() 

/*Set some properties of related controls*/ 
m_rtdRecv.SetAutoURLDetect(TRUE); 
m_rtdRecv.SetEventMask(ENM_CHANGE); 
USES_CONVERSION; 
/*Set chat edit box and information display box The font attributes of */ 
//m_cfDefault.cbSize = sizeof(CHARFORMAT); 
//m_cfDefault.dwMask = CFM_BOLD|CFM_COLOR|CFM_FACE|CFM_ITALIC|CFM_UNDERLINE; 
//m_cfDefault.dwEffects = CFE_BOLD|CFE_ITALICy;
Height_cfDefault.LINE |Height_UNDER  20*1440/96; 
//m_cfDefault.yOffset = 0; 
//m_cfDefault.crTextColor = RGB(255,0,0); 
//m_cfDefault.bCharSet = 0; 
//m_cfDefault.bPitchAndFamily = 0; 
//strcpy(W2A (m_cfDefault.szFaceName), "Song Ti"); 
= the sizeof m_cfDefault.cbSize (the CHARFORMAT); 
m_rtdRecv.GetDefaultCharFormat (m_cfDefault); 
m_cfDefault.yHeight = 200 is; 
m_cfDefault.dwEffects = 0; 
m_cfDefault.crTextColor the RGB = (0, 0, 255); 
m_rtdRecv.SetDefaultCharFormat (m_cfDefault); 
m_rtdRecv. LimitText(1024); 
m_rtdSend.SetDefaultCharFormat(m_cfDefault); 
m_rtdSend.LimitText(1024); 

//Display receiving window message 
void CDemoDlgMsg::ShowRecvText(CString str) 

/*If you need to display in a new line*/ 
m_rtdRecv.ReplaceSel(str) ; 
m_rtdRecv.SetSel(-1, -1); 
m_rtdRecv.ReplaceSel(L"/r/n"); 
}