How to insert colored text into CRichEditCtrl

23 03 2009

description4

 

 

Sometimes we need to insert text with different colors into our CRichEditCtrl. Not only just changes the color of the text but also need to format the characters in the control.

richeditcoloredtxt

 

howcanidoit4

 

 

CRichEditCtrl provides a function SetSelectionCharFormat for that. Actually this function passing a pointer to a CHARFORMAT structure containing the new character formatting attributes. Please see the different members of this structure in the MSDN.

mycodesnippet4

 

 

void InsertColoredTextIntoRichEditCtrl()
{
   CHARFORMAT cf;
  
   cf.cbSize      = sizeof(cf);
   cf.dwMask      = CFM_BOLD|CFM_COLOR  ;
   cf.dwEffects   = CFE_BOLD|~CFE_AUTOCOLOR  ;
  
   myRichEditCtrl.SetWindowText("I want colored text");
  
   cf.crTextColor = RGB(0,255,0); 
  
   myRichEditCtrl.SetSel(0,1);
   myRichEditCtrl.SetSelectionCharFormat(cf);
  
   cf.crTextColor = RGB(255,0,0);
   myRichEditCtrl.SetSel(2,6);
   myRichEditCtrl.SetSelectionCharFormat(cf);
  
   cf.crTextColor = RGB(0,0, 255);
   myRichEditCtrl.SetSel(7,15);
   myRichEditCtrl.SetSelectionCharFormat(cf);
  
   cf.crTextColor = RGB(220,69, 133);
   myRichEditCtrl.SetSel(15,19);
   myRichEditCtrl.SetSelectionCharFormat(cf);
}

mynote6

 

 

If you are using a rich edit control in a dialog box, dont forget to call AfxInitRichEdit once before the dialogbox is displayed.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: