Mega Code Archive

 
Categories / Delphi / Graphic
 

Change font color, size, style, and back color of certain words inside a rich edit

Title: Change font color, size, style, and back color of certain words inside a rich edit. Question: Do you want to have a nice looking rich edit? Answer: This procedure will search and change the attributes (font name, font size, font color, font style, and back color) of certain words inside a rich edit control. Try the example. USES RichEdit; ..................................................... type TTextAttributes = record Font : TFont; BackColor : TColor; end; ..................................................... ..................................................... ..................................................... procedure SetTextColor(oRichEdit : TRichEdit; sText : String; rAttributes : TTextAttributes); var iPos : Integer; iLen : Integer; Format: CHARFORMAT2; begin FillChar(Format, SizeOf(Format), 0); Format.cbSize := SizeOf(Format); Format.dwMask := CFM_BACKCOLOR; Format.crBackColor := rAttributes.BackColor; iPos := 0; iLen := Length(oRichEdit.Lines.Text) ; iPos := oRichEdit.FindText(sText, iPos, iLen, []); while iPos -1 do begin oRichEdit.SelStart := iPos; oRichEdit.SelLength := Length(sText) ; oRichEdit.SelAttributes.Color := rAttributes.Font.Color; oRichEdit.SelAttributes.Size := rAttributes.Font.Size; oRichEdit.SelAttributes.Style := rAttributes.Font.Style; oRichEdit.SelAttributes.Name := rAttributes.Font.Name; oRichEdit.Perform(EM_SETCHARFORMAT, SCF_SELECTION, Longint(@Format)); iPos := oRichEdit.FindText(sText,iPos + Length(sText),iLen, []) ; end; end; ..................................................... Example: ..................................................... var rAttrib : TTextAttributes; begin RichEdit1.Lines.Add('Delphi is great once you know how to use it.'); rAttrib.Font := TFont.Create; rAttrib.Font.Color := clWhite; rAttrib.Font.Size := 16; rAttrib.Font.Style := [fsBold]; rAttrib.BackColor := clRed; SetTextColor(RichEdit1,'Delphi',rAttrib); //Change another word attributes. rAttrib.Font.Color := clYellow; rAttrib.Font.Size := 10; rAttrib.Font.Style := [fsBold,fsItalic]; rAttrib.BackColor := clBlue; SetTextColor(RichEdit1,'once you',rAttrib); rAttrib.Font.Free; //Now free the font. end; .....................................................