Click here to Skip to main content
15,881,281 members
Articles / Desktop Programming / Windows Forms
Article

Links with arbitrary text in a RichTextBox

Rate me:
Please Sign up or sign in to vote.
4.84/5 (80 votes)
1 Jan 2005CPOL4 min read 679.3K   11.9K   96   210
An extended RichTextBox that allows to enter links <i>not</i> starting with one of the standard protocols.

Sample Image - RichTextBoxLinks.gif

Introduction

From time to time, somebody asks in the forums if it is possible to add links to a RichTextBox that don't start with http://, ftp:// or another one of the 'standard' protocols.

Well, here's the solution.

Background

The standard RichTextBox has a quite handy property: DetectUrls.

When this property is set, every time the text in the RichTextBox is changed, the text is parsed for URLs and the matching text ranges are formatted as links (underlined, blue foreground by default).

The problem is, only links starting with one of the recognized protocols (http:, file:, mailto:, ftp:, https:, gopher:, nntp:, prospero:, telnet:, news:, wais:, outlook:) are recognized and reformatted. When you don't want such a reference, you're stumped, because the standard RichTextBox doesn't allow for manually setting the link style at all.

Fortunately, the .NET RichTextBox is only a wrapper around the Win32 RichEdit control, and so its functionality can be extended by adding the necessary wrappers to send the messages the RichEdit control needs.

How the RichEdit control manages style changes

The RichEdit control defines two sets of messages that control how part of the text is being rendered. One set EM_GETCHARFORMAT, EM_SETCHARFORMAT) is responsible for setting and querying formatting options for character ranges inside a paragraph, the other one (EM_GETPARAFORMAT, EM_SETPARAFORMAT) sets/queries formatting options for entire paragraphs (like alignment, for example).

We'll use the first one to set the desired style.

When you look up EM_SETCHARFORMAT's documentation, you'll see that a CHARFORMAT structure is used to transmit the formatting information. For recent versions of the RichEdit control (V2.0 and up), this structure is extended to a CHARFORMAT2 struct holding additional information.

The definition of this CHARFORMAT2 struct as taken from the platform SDK:

typedef struct _charformat2 {
    UINT cbSize;
    DWORD dwMask;
    DWORD dwEffects;
    LONG yHeight;
    LONG yOffset;
    COLORREF crTextColor;
    BYTE bCharSet;
    BYTE bPitchAndFamily;
    TCHAR szFaceName[LF_FACESIZE];
    WORD wWeight;
    SHORT sSpacing;
    COLORREF crBackColor;
    LCID lcid;
    DWORD dwReserved;
    SHORT sStyle;
    WORD wKerning;
    BYTE bUnderlineType;
    BYTE bAnimation;
    BYTE bRevAuthor;
    BYTE bReserved1;
} CHARFORMAT2;

Among other information, there are two members controlling formatting aspects that can be expressed as flags, i.e., part of the text has this formatting property set or not. These members are dwMask and dwEffects. dwMask is used to specify whether you want to set/query a given formatting option and dwEffect holds the actual value.

There's a flag CFE_LINK that does just what we want: give part of the text the link appearance and behaviour.

Wrapping up the structs and messages

In order to tell the RichEdit control that we want to assign a given character format to part of the text, you need to send the Windows message EM_SETCHARFORMAT to the control. If you're interested in how exactly the Win32 struct has been wrapped and how SendMessage() has been declared, please take a look at the source code.

Rewriting the struct declarations was quite straightforward, the only member that requires a little thought is szFaceName, because C# structs can't be declared to hold a character array of a given size. Microsoft accounted for this case, however, by supplying the SizeConst field to the MarshalAs attribute.

Using the class

When you use the extended RichTextBox, you'll have several new methods available:

C#
public void InsertLink(string text);
public void InsertLink(string text, int position);

to insert a link at a given position (or at the current insert position if not specified).

In case the link text is not suitable as a result of the LinkClicked event (for example, if you have several identical link text that you want to reference different hyperlinks), there are two additional methods where you can specify an additional hyperlink string:

C#
public void InsertLink(string text, string hyperlink);
public void InsertLink(string text, string hyperlink, int position);

They behave like the previous two methods, but after the link text itself, the hyperlink string is added invisibly, separated by a hash ('#'). For example, calling:

C#
InsertLink("online help", "myHelpFile.chm");

will give "online help#myHelpFile.chm" in the LinkClickedEventArgs. That way, you can manage link texts and hyperlinks independently.

The base methods to set or clear the link character format are:

C#
public void SetSelectionLink(bool link);
public int GetSelectionLink();

Both operate on the current selection. The return value of GetSelectionLink() has been made int instead of bool because the current selection can contain link - and regular parts and thus yield inconsistent results. This is reflected by returning -1, whereas consistent link style yields 1 and consistent non-link style yields 0.

Caveats

There's one detail to take care of. By default, the DetectUrls property of the standard RichTextBox is set, so whatever you type is reformatted automatically.

My extension turns this property off by default because it can interfere with links that have been added programmatically. When the DetectUrls property is set to true and you modify the text adjacent to one of your links, the link formatting will be lost. This does not happen when DetectUrls is set to false, so I recommend you leave it switched off.

Possible extensions

Just like I added support for CFE_LINK, it should be a breeze to add support for other formatting flags as well (for example, CFE_SUBSCRIPT or CFE_SUPERSCRIPT) to add new formatting options not available out of the box.

The necessary flag definitions are included in the source code already so that you don't have to look them up in the platform SDK anymore.

Modification History

  • 02.01.2005

    Initial release.

  • 03.01.2005

    Added support for invisible hyperlink strings.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) 4voice AG
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Links Lost When Saving Pin
mav.northwind16-May-05 19:44
mav.northwind16-May-05 19:44 
GeneralRe: Links Lost When Saving Pin
pal118329-Sep-06 23:23
pal118329-Sep-06 23:23 
GeneralImage EMF and Link Pin
nhooge11-May-05 1:01
sussnhooge11-May-05 1:01 
Generalutf-8 strings Pin
Mahdi.Jabbari8-May-05 1:38
Mahdi.Jabbari8-May-05 1:38 
GeneralRe: utf-8 strings Pin
Mahdi.Jabbari8-May-05 4:14
Mahdi.Jabbari8-May-05 4:14 
GeneralRe: utf-8 strings Pin
fethigurcan24-Feb-06 3:48
fethigurcan24-Feb-06 3:48 
GeneralRe: utf-8 strings Pin
nesaver8514-Oct-07 18:48
nesaver8514-Oct-07 18:48 
GeneralVB.NET Code Issue Pin
scriptsure@comcast.net3-May-05 10:33
scriptsure@comcast.net3-May-05 10:33 
Mav do you see what is wrong with this vb.net code. It returns 0 off the sendmessage. It is in a usercontrol:

Private Structure CHARFORMAT2_STRUCT
Public cbSize As Int32
Public dwMask As Int32
Public dwEffects As Int32
Public yHeight As Int32
Public yOffset As Int32
Public crTextColor As Int32
Public bCharSet As Byte
Public bPitchAndFamily As Byte

Public szFaceName() As Char
Public wWeight As UInt16
Public sSpacing As UInt16
Public crBackColor As Integer ' Color.ToArgb() -> int
Public lcid As Integer
Public dwReserved As Integer
Public sStyle As Int16
Public wKerning As Int16
Public bUnderlineType As Byte
Public bAnimation As Byte
Public bRevAuthor As Byte
Public bReserved1 As Byte
End Structure


Private Overloads Declare Auto Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As IntPtr, _
ByVal msg As Int32, _
ByVal wParam As IntPtr, _
ByVal lParam As IntPtr) As IntPtr
'End Function

Private Const WM_USER As Integer = &H400&
Private Const EM_FORMATRANGE As Integer = WM_USER + 57
Private Const EM_GETCHARFORMAT As Integer = WM_USER + 58
Private Const EM_SETCHARFORMAT As Integer = WM_USER + 68

Private Const SCF_SELECTION As Integer = &H1&
Private Const SCF_WORD As Integer = &H2&
Private Const SCF_ALL As Integer = &H4&

#Region "CHARFORMAT2 Flags"
Private Const CFE_BOLD As Int32 = &H1&
Private Const CFE_ITALIC As Int32 = &H2&
Private Const CFE_UNDERLINE As Int32 = &H4&
Private Const CFE_STRIKEOUT As Int32 = &H8&
Private Const CFE_PROTECTED As Int32 = &H10&
Private Const CFE_LINK As Int32 = &H20&
Private Const CFE_AUTOCOLOR As Int32 = &H40000000&
Private Const CFE_SUBSCRIPT As Int32 = &H10000& 'Superscript and subscript are
Private Const CFE_SUPERSCRIPT As Int32 = &H20000& 'mutually exclusive

Private Const CFM_SMALLCAPS As Integer = &H40& ' (*)
Private Const CFM_ALLCAPS As Integer = &H80& ' Displayed by 3.0
Private Const CFM_HIDDEN As Integer = &H100& ' Hidden by 3.0
Private Const CFM_OUTLINE As Integer = &H200& ' (*)
Private Const CFM_SHADOW As Integer = &H400& ' (*)
Private Const CFM_EMBOSS As Integer = &H800& ' (*)
Private Const CFM_IMPRINT As Integer = &H1000& ' (*)
Private Const CFM_DISABLED As Integer = &H2000&
Private Const CFM_REVISED As Integer = &H4000&

Private Const CFM_BACKCOLOR As Integer = &H4000000&
Private Const CFM_LCID As Integer = &H2000000&
Private Const CFM_UNDERLINETYPE As Integer = &H800000& ' Many displayed by 3.0
Private Const CFM_WEIGHT As Integer = &H400000&
Private Const CFM_SPACING As Integer = &H200000& ' Displayed by 3.0
Private Const CFM_KERNING As Integer = &H100000& ' (*)
Private Const CFM_STYLE As Integer = &H80000& ' (*)
Private Const CFM_ANIMATION As Integer = &H40000& ' (*)
Private Const CFM_REVAUTHOR As Integer = &H8000&


Private Const CFM_BOLD As Int32 = &H1&
Private Const CFM_ITALIC As Int32 = &H2&
Private Const CFM_UNDERLINE As Int32 = &H4&
Private Const CFM_STRIKEOUT As Int32 = &H8&
Private Const CFM_PROTECTED As Int32 = &H10&
Private Const CFM_LINK As Int32 = &H20&
'Private Const CFM_SIZE As Int32 = &H80000000&
Private Const CFM_COLOR As Int32 = &H40000000&
Private Const CFM_FACE As Int32 = &H20000000&
Private Const CFM_OFFSET As Int32 = &H10000000&
Private Const CFM_CHARSET As Int32 = &H8000000&
Private Const CFM_SUBSCRIPT As Int32 = CFE_SUBSCRIPT Or CFE_SUPERSCRIPT
Private Const CFM_SUPERSCRIPT As Int32 = CFM_SUBSCRIPT

Private Const CFU_UNDERLINENONE As Byte = &H0&
Private Const CFU_UNDERLINE As Byte = &H1&
Private Const CFU_UNDERLINEWORD As Byte = &H2& ' (*) displayed as ordinary underline
Private Const CFU_UNDERLINEDOUBLE As Byte = &H3& ' (*) displayed as ordinary underline
Private Const CFU_UNDERLINEDOTTED As Byte = &H4&
Private Const CFU_UNDERLINEDASH As Byte = &H5&
Private Const CFU_UNDERLINEDASHDOT As Byte = &H6&
Private Const CFU_UNDERLINEDASHDOTDOT As Byte = &H7&
Private Const CFU_UNDERLINEWAVE As Byte = &H8&
Private Const CFU_UNDERLINETHICK As Byte = &H9&
Private Const CFU_UNDERLINEHAIRLINE As Byte = &HA& ' (*) displayed as ordinary underline
#End Region

#End Region

#Region " Methods "

'/
'/ Insert a given text as a link into the RichTextBox at the current insert position.
'/
'/ Text to be inserted
Public Overloads Sub InsertLink(ByVal [text] As String)
InsertLink([text], Me.RichTextBox.SelectionStart)
End Sub

'/
'/ Insert a given text at a given position as a link.
'/
'/ Text to be inserted
'/ Insert position
Public Overloads Sub InsertLink(ByVal [text] As String, ByVal position As Integer)
If position < 0 OrElse position > Me.Text.Length Then
Throw New ArgumentOutOfRangeException("position")
End If
Me.RichTextBox.SelectionStart = position
Me.RichTextBox.SelectedText = [text]
Me.RichTextBox.Select(position, [text].Length)
Me.SetSelectionLink(True)
Me.RichTextBox.Select(position + [text].Length, 0)
End Sub

'/
'/ Insert a given text at at the current input position as a link.
'/ The link text is followed by a hash (#) and the given hyperlink text, both of
'/ them invisible.
'/ When clicked on, the whole link text and hyperlink string are given in the
'/ LinkClickedEventArgs.
'/
'/ Text to be inserted
'/ Invisible hyperlink string to be inserted
Public Overloads Sub InsertLink(ByVal [text] As String, ByVal hyperlink As String)
InsertLink([text], hyperlink, Me.RichTextBox.SelectionStart)
End Sub

'/
'/ Insert a given text at a given position as a link. The link text is followed by
'/ a hash (#) and the given hyperlink text, both of them invisible.
'/ When clicked on, the whole link text and hyperlink string are given in the
'/ LinkClickedEventArgs.
'/
'/ Text to be inserted
'/ Invisible hyperlink string to be inserted
'/ Insert position
Public Overloads Sub InsertLink(ByVal [text] As String, ByVal hyperlink As String, ByVal position As Integer)
If position < 0 OrElse position > Me.Text.Length Then
Throw New ArgumentOutOfRangeException("position")
End If
Me.RichTextBox.SelectionStart = position
Me.RichTextBox.SelectedRtf = "{\rtf1\ansi " + [text] + "\v #" + hyperlink + "\v0}"
Me.RichTextBox.Select(position, [text].Length + hyperlink.Length + 1)
Me.SetSelectionLink(True)
Me.RichTextBox.Select(position + [text].Length + hyperlink.Length + 1, 0)
End Sub

'/
'/ Set the current selection's link style
'/
'/ true: set link style, false: clear link style
Public Sub SetSelectionLink(ByVal link As Boolean)
SetSelectionStyle(CFM_LINK, IIf(link, CFE_LINK, 0))
End Sub

'/
'/ Get the link style for the current selection
'/
'/ 0: link style not set, 1: link style set, -1: mixed
Public Function GetSelectionLink() As Integer
Return GetSelectionStyle(CFM_LINK, CFE_LINK)
End Function

Private Sub SetSelectionStyle(ByVal mask As Int32, ByVal effect As Int32)
Dim cf As New CHARFORMAT2_STRUCT
cf.cbSize = CType(Marshal.SizeOf(cf), Int32)
cf.dwMask = mask
cf.dwEffects = effect

Dim wpar As New IntPtr(SCF_SELECTION)
Dim lpar As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(cf))
Marshal.StructureToPtr(cf, lpar, False)

Dim res As IntPtr = SendMessage(Me.RichTextBox.Handle, EM_SETCHARFORMAT, wpar, lpar)

Marshal.FreeCoTaskMem(lpar)
End Sub

Private Function GetSelectionStyle(ByVal mask As Int32, ByVal effect As Int32) As Integer
Dim cf As New CHARFORMAT2_STRUCT
cf.cbSize = CType(Marshal.SizeOf(cf), Int32)
cf.szFaceName = New Char(32) {}

Dim wpar As New IntPtr(SCF_SELECTION)
Dim lpar As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(cf))
Marshal.StructureToPtr(cf, lpar, False)

Dim res As IntPtr = SendMessage(Me.RichTextBox.Handle, EM_GETCHARFORMAT, wpar, lpar)

cf = CType(Marshal.PtrToStructure(lpar, GetType(CHARFORMAT2_STRUCT)), CHARFORMAT2_STRUCT)

Dim state As Integer

' dwMask holds the information which properties are consistent throughout the selection:
If (cf.dwMask And mask) = mask Then
If (cf.dwEffects And effect) = effect Then
state = 1
Else
state = 0
End If
Else
state = -1
End If

Marshal.FreeCoTaskMem(lpar)
Return state
End Function
#End Region
GeneralPainting Issue Pin
alineurope12-Apr-05 11:38
alineurope12-Apr-05 11:38 
GeneralRe: Painting Issue Pin
mav.northwind12-Apr-05 19:44
mav.northwind12-Apr-05 19:44 
GeneralRe: Painting Issue Pin
alineurope13-Apr-05 3:42
alineurope13-Apr-05 3:42 
GeneralHelp with conversion to VB Pin
al1234530-Mar-05 3:06
al1234530-Mar-05 3:06 
GeneralRe: Help with conversion to VB Pin
mav.northwind30-Mar-05 3:24
mav.northwind30-Mar-05 3:24 
GeneralRe: Help with conversion to VB Pin
alineurope30-Mar-05 3:54
alineurope30-Mar-05 3:54 
GeneralRe: Help with conversion to VB Pin
scriptsure@comcast.net3-May-05 7:46
scriptsure@comcast.net3-May-05 7:46 
GeneralRe: Help with conversion to VB Pin
mot.kracker4-Sep-08 20:45
mot.kracker4-Sep-08 20:45 
GeneralUnicode not supported Pin
mudmantis27-Mar-05 7:06
mudmantis27-Mar-05 7:06 
GeneralRe: Unicode not supported Pin
mav.northwind24-Aug-05 19:56
mav.northwind24-Aug-05 19:56 
GeneralIssue with adding link Pin
tivac24-Mar-05 7:08
tivac24-Mar-05 7:08 
GeneralRe: Issue with adding link Pin
tivac24-Mar-05 7:18
tivac24-Mar-05 7:18 
GeneralRe: Issue with adding link Pin
mav.northwind3-Apr-05 21:26
mav.northwind3-Apr-05 21:26 
GeneralUnderline Pin
chettu9-Mar-05 17:36
chettu9-Mar-05 17:36 
GeneralRe: Underline Pin
mav.northwind9-Mar-05 20:00
mav.northwind9-Mar-05 20:00 
GeneralRe: Underline Pin
chettu9-Mar-05 20:10
chettu9-Mar-05 20:10 
GeneralRe: Underline Pin
mav.northwind9-Mar-05 20:30
mav.northwind9-Mar-05 20:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.