As promised earlier, I've added the ability to change the background colour of the text. I've also made one or two minor changes to the rest of the code, which I'll detail at the end.
Background Colour
Changing the background colour is a simple matter. It works in exactly the same way as changing the underline style, by setting the character format. Since we're dealing with Color here, we need to be using System.Drawing. Then it's just a matter of sending the correct message:
+ Code to set the background colour for a selected region.
/// <summary>
/// Gets or sets the background color to apply to the
/// current selection or insertion point.
/// </summary>
/// <remarks>
/// If the selection contains more than one background
/// color, then this property will indicate it by
/// returning Color.Empty.
/// </remarks>
public Color SelectionBackColor
{
get
{
CHARFORMAT fmt = new CHARFORMAT();
fmt.cbSize = Marshal.SizeOf( fmt );
// Get the background color.
SendMessage( new HandleRef( this, Handle ), EM_GETCHARFORMAT,
SCF_SELECTION, ref fmt );
// Default to Color.Empty as there could be
// several colors present in this selection.
if ( ( fmt.dwMask & CFM_BACKCOLOR ) == 0 )
return Color.Empty;
// Deal with the weird Windows color format.
int backCol = fmt.crBackColor;
Color ret = ColorTranslator.FromWin32( backCol );
return ret;
}
set
{
CHARFORMAT fmt = new CHARFORMAT();
fmt.cbSize = Marshal.SizeOf( fmt );
fmt.dwMask = CFM_BACKCOLOR;
// Deal with the weird Windows color format.
fmt.crBackColor = ColorTranslator.ToWin32( value );
// Set the background color.
SendMessage( new HandleRef( this, Handle ), EM_SETCHARFORMAT,
SCF_SELECTION, ref fmt );
}
}
And there's one more constant to add:
private const int CFM_BACKCOLOR = 67108864;
That should now enable us to change the background colour of the text. Simple, wasn't it?
Alterations
Notice in the middle of the get method above, we return Color.Empty by default. This is because that return value is used when more than one colour is selected (like in Word when you select across several fonts and the font selection combobox goes blank). A similar approach can be taken in the alignment and underline properties presented previously.
All you have to do is add an entry to the relevant enumeration called "None" (or whatever), probably equal to zero, and return it in the appropriate get method where it says "Default to <whatever>".
Conclusion
That's it for AdvRichTextBox. If anyone is actually reading this and wants me to add more functionality (or post complete source), just leave a comment or send me an email.