4

I have a TRichEdit control containing source code. I want to set the background color of a single line.

I know how to set the text color, but isn't there a way to set the background color as well? I'm not talking about the entire background colour for the whole control, only how to change one single line.

Do I really have to write a custom control to do this?

Max Kielland
  • 5,627
  • 9
  • 60
  • 95

2 Answers2

6

There is no TRichEdit property for setting the background color of individual characters/lines. However, you can use the Win32 API SendMessage() function, or the TRichEdit's own Perform() method, to send it an EM_SETCHARFORMAT message, specifying a CHARFORMAT2 structure whose crBackColor field is set to the desired color. You can apply formatting to existing characters by highlighting them first, or you can apply formatting to the current caret position if there is no selection.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Ahh, this was the answer I was looking for. (I know that TRichEdit doesn't have this. I wouldn't have asked it here if it was ;) – Max Kielland Dec 16 '13 at 23:39
  • I'm back on this program again and this time I want to set the background color of the entire line, not only where there is text. I want to highligt an entire row from left to right even if it is empty. Is this possible? – Max Kielland Jun 13 '18 at 01:25
  • 1
    You can only select characters, not lines. If a line is empty, it has no characters to select. In which case, your only option is to subclass the RichEdit and custom draw it manually. Otherwise, use a different component that has more options available, such as SynEdit. – Remy Lebeau Jun 13 '18 at 02:10
2

The MSDN on RTF specifies \cbN, where N is the color index.

Other searches suggest this is not supported by a lot of applications (OS X's native RTF viewer, Microsoft Word) so maybe you should look for a custom solution.

Jongware
  • 22,200
  • 8
  • 54
  • 100