Click here to Skip to main content
Click here to Skip to main content
Go to top

Links with arbitrary text in a RichTextBox

, 1 Jan 2005
Rate this:
Please Sign up or sign in to vote.
An extended RichTextBox that allows to enter links not 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:

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:

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:

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:

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)

Share

About the Author

mav.northwind
Software Developer (Senior) 4voice AG
Germany Germany
No Biography provided

Comments and Discussions

 
QuestionHow would i turn this into a Control? PinmemberMember 350952314-Jun-09 17:27 
NewsUpdated version Including Link Editing, custom formatting and some fixes PinmemberFade (Amit BS)30-Apr-09 9:55 
GeneralRe: Updated version Including Link Editing, custom formatting and some fixes Pinmember[CC]20-Sep-10 0:17 
AnswerRe: Updated version Including Link Editing, custom formatting and some fixes PinmemberFade (Amit BS)20-Sep-10 7:39 
GeneralRe: Updated version Including Link Editing, custom formatting and some fixes Pinmemberchrisbray17-Oct-10 3:08 
QuestionSending mail using Lotus Notes 6.5.5 with VB 2008 Pinmemberbrindhakr1-Mar-09 23:39 
GeneralAutoDectect MyLinks Pinmemberghbloos14-Jan-09 8:14 
GeneralGeneric solution for i18n problem PinmemberTsuda Kageyu29-Dec-08 15:20 
Question??? Pinmembermorning_star21200528-Oct-08 16:24 
GeneralLink Color, I neeed help PinmemberEng.Habeba13-Jul-08 4:34 
GeneralRe: Link Color, I neeed help Pinmembermav.northwind13-Jul-08 6:23 
GeneralRe: Link Color, I neeed help PinmemberEng.Habeba13-Jul-08 21:10 
GeneralRe: Link Color, I neeed help PinmemberAleksei Krassovskikh31-Aug-08 23:14 
GeneralRe: Link Color, I neeed help Pinmemberpsouza4micronet14-Aug-09 6:39 
QuestionHow do I remove a link and rtf markup for the link? PinmemberMaddieITI7-May-08 6:06 
AnswerRe: How do I remove a link and rtf markup for the link? PinmemberItalianCousin7-Aug-09 23:19 
GeneralGet the position of the link Pinmemberbachi1234-Mar-08 10:57 
GeneralRe: Get the position of the link Pinmemberbachi1236-Mar-08 5:13 
GeneralRe: Get the position of the link Pinmembertarkster218-Jan-10 10:55 
GeneralLicense PinmemberGreg Campbell9-Jan-08 12:13 
QuestionCool..What about images ?? PinmemberMaskina19-Nov-07 7:59 
GeneralNice Project! Pinmemberwchoi985-Nov-07 11:10 
GeneralUsing \ or { and } characters with the invisible hyperlink option. PinmemberAli R.25-Sep-07 10:39 
QuestionProtected links? PinmemberBMcBSF23-Aug-07 12:02 
AnswerRe: Protected links? PinmemberJohn C12-Nov-08 10:12 
Hi, what you describe is a serious problem with using hyperlink technique in this article, however I *have* found a way to accomplish it.
The reason your first method of including the \protect tag inside the rtf doesn't result in a link is because the protect tag prevents the link from being set on that text later on.
 
Instead use the SelectionProtected property to set protect *after* the link has been set, in other words change the code in the InsertLink method:
 
//Original code fragment
this.Select(position, text.Length + hyperlink.Length + 1);
this.SetSelectionLink(true);
 
//Put this right after SetSelectionLink above
this.SelectionProtected = true;
 
This actually solves a number of other problems as well including more than one hyperlink per line, editing on either side of the hyperlink without breaking the link etc but introduces a new one which is that the user would not be able to alter the link in any way without un protecting it first. This is probably best accomplished in the UI somehow when they attempt to type in protected text perhaps or through a system of link management in the UI like Word does when dealing with links in a document etc.
 

"It's so simple to be wise. Just think of something stupid to say and then don't say it."
-Sam Levenson

GeneralRe: Protected links? PinmemberMember 391992512-Apr-12 8:54 
Question64-bit VS2005 PinmemberJim Adams30-Apr-07 11:53 
AnswerRe: 64-bit VS2005 PinmemberJohn C12-Nov-08 7:26 
GeneralBookmarks Pinmembertaxidev14-Feb-07 0:56 
QuestionRtf reloading PinmemberEli Yukelzon23-Dec-06 2:36 
AnswerRe: Rtf reloading Pinmembermav.northwind24-Dec-06 5:13 
GeneralRe: Rtf reloading PinmemberEli Yukelzon24-Dec-06 5:41 
GeneralCan't insert text after a link PinmemberAaron sher2-Dec-06 15:10 
GeneralRe: Can't insert text after a link PinmemberAndrewInEssex11-Jan-09 6:32 
GeneralRe: Can't insert text after a link PinmemberAaron sher12-Jan-09 3:17 
GeneralRe: Can't insert text after a link Pinmemberlonewolfdev29-Apr-11 17:01 
Generalapplication maximize PinmemberManjunath V Hiremath7-Nov-06 22:38 
GeneralRe: application maximize Pinmembermav.northwind8-Nov-06 8:23 
GeneralRe: application maximize PinmemberManjunath V Hiremath17-Nov-06 17:21 
GeneralRe: application maximize Pinmembermav.northwind17-Nov-06 19:59 
GeneralRichTextBox PinmemberManjunath V Hiremath7-Nov-06 17:55 
GeneralRe: RichTextBox Pinmembermav.northwind8-Nov-06 8:24 
GeneralLink without Underline Pinmemberchinajuanbob6-Nov-06 16:21 
GeneralRe: Link without Underline Pinmembermav.northwind8-Nov-06 8:26 
QuestionIs selection in a link? Pinmemberalo vatan3-Nov-06 2:26 
AnswerRe: Is selection in a link? Pinmembermav.northwind8-Nov-06 8:31 
QuestionCan't get this to work Pinmemberbrypie25-Oct-06 1:15 
AnswerRe: Can't get this to work Pinmembermav.northwind25-Oct-06 18:33 
GeneralRe: Can't get this to work Pinmemberbrypie25-Oct-06 21:48 
GeneralThis article PinmemberHeritos Gger13-Oct-06 4:32 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 2 Jan 2005
Article Copyright 2005 by mav.northwind
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid