The RichTextBox com control actually supports changing the underline style and colour, however the .net wrapp does not let you control how to set and use this facility.  To use this facility we put in two new functions, SelectionUnderlineStyle and SelectionUnderlineColor.  These properties can be used to get or set the underline style and colour in the RichTextBox.

The system works by using the windows messages EM_GETCHARFORMAT and EM_SETCHARFORMAT, these messages use the CHARFORMAT2 structure to setup various aspects of the character format.  The dwMask is used to control what aspects of the structure is filled in and which bits are not.

Code for the CHARFORMAT2 class

[StructLayout(LayoutKind.Sequential)]
private struct CHARFORMAT2
{
    public int cbSize;
    public uint dwMask;
    public uint dwEffects;
    public int yHeight;
    public int yOffset;
    public int crTextColor;
    public byte bCharSet;
    public byte bPitchAndFamily;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
    public char[] szFaceName;
    public short wWeight;
    public short sSpacing;
    public int crBackColor;
    public int LCID;
    public uint dwReserved;
    public short sStyle;
    public short wKerning;
    public byte bUnderlineType;
    public byte bAnimation;
    public byte bRevAuthor;
}
 

The above code shows how to use structures to interact with unmanaged code.  The attribute at the top saying the structure is sequential is needed to stop any sorts of optimisation being done on the structure and to make it layed out in the same scheme as unmanaged code (c or C++).  The MarshalAs reference is also needed to make the system correctly marshal the array from the unamanged code into the managed code.  The main pieces used inside this structure is the UnderType byte, which is defined using the UnderlineStyle enum defined inside the RichTextBox file.  So you can get nice wavey lines or dashed ones, which ever ones you want.  The underline colour of the underline is only selectable from a limited list of underline colour types.  The colour types are also defined in the enum UnderlineColor also defined in the RichTextBox code.

The main part of the RichTextBox was included in yesterdays blog on this subject.