Click here to Skip to main content
15,442,081 members
Articles / Desktop Programming / Windows Forms
Article
Posted 1 Jan 2005

Stats

625.8K views
11.5K downloads
95 bookmarked

Links with arbitrary text in a RichTextBox

Rate me:
Please Sign up or sign in to vote.
4.83/5 (79 votes)
1 Jan 2005CPOL4 min read
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

 
QuestionHow can I release this project with DetectUrl=true??? Pin
DeftVK3-Oct-06 3:42
MemberDeftVK3-Oct-06 3:42 
GeneralTry replace fragment of code... Pin
DeftVK2-Oct-06 19:51
MemberDeftVK2-Oct-06 19:51 
QuestionHow can I remove the link Pin
montapas17-Aug-06 3:12
Membermontapas17-Aug-06 3:12 
AnswerRe: How can I remove the link Pin
mav.northwind17-Aug-06 9:37
Membermav.northwind17-Aug-06 9:37 
GeneralRichTextBox with icons as links Pin
fiechter30-Jun-06 3:42
Memberfiechter30-Jun-06 3:42 
Questionhow can i cancel this link ? Pin
df3e24-May-06 17:43
Memberdf3e24-May-06 17:43 
AnswerRe: how can i cancel this link ? Pin
mav.northwind30-Jun-06 9:26
Membermav.northwind30-Jun-06 9:26 
GeneralRichTextBox using in Outlook Add-In Pin
fethigurcan24-Feb-06 3:44
Memberfethigurcan24-Feb-06 3:44 
Hello

I'm developing an add-in for Outlook with C# (.NET 1.1)

My add-in is for corporete use and it can be E-Mail and SMS the same message to recipients.

I developed a "new sms..." window that is a similar to outlook's "new message" window.

Everything is done except the (To [in the 'new message' window]) box. You know, it is not an standard TextBox and uses some links to contact objects.. it is like a rich text box actually.

Anyway,

I had to use/develop a customized (To) box. And i started from this fine example and developed a working (To) box...

After that i applied this box to my Outlook-Add-in.. and it was really a disaster Cry | :(( (
it did not work fine, can't handle correct position values etc.

I don't know how, but i discovered, the outlook (may be all office apps) replaces the RichTextBox class to own RichTextBox class. And if you use a custom control derived from RichTextBox, it's parent also replaced by this Outlook's RichTextBox class.. Cry | :(( ((

It is like to original class but some different that i see, speacially the Selection??? properties. (it doesn't calculate the '#www.sss.com' hidden text's length)

May be it is same as same with the original Richtextbox control but some properties's default values are changed by outlook...

Some body know about any property to switch between "calculate hidden text" or "do not calculate"??

Thank you;

Note: I will also publish my control as codeproject article soon
GeneralRe: RichTextBox using in Outlook Add-In Pin
fethigurcan24-Feb-06 4:39
Memberfethigurcan24-Feb-06 4:39 
GeneralRe: RichTextBox using in Outlook Add-In Pin
sim*6-Dec-06 6:55
Membersim*6-Dec-06 6:55 
GeneralForm Border &amp; Title Bar color Pin
eddy_mi23-Nov-05 8:24
Membereddy_mi23-Nov-05 8:24 
GeneralRe: Form Border &amp; Title Bar color Pin
mav.northwind17-Aug-06 9:46
Membermav.northwind17-Aug-06 9:46 
GeneralRestoring links in the RTF Pin
erking7-Oct-05 3:01
Membererking7-Oct-05 3:01 
GeneralRe: Restoring links in the RTF Pin
mav.northwind7-Oct-05 4:03
Membermav.northwind7-Oct-05 4:03 
GeneralRe: Restoring links in the RTF Pin
erking8-Oct-05 7:17
Membererking8-Oct-05 7:17 
GeneralRe: Restoring links in the RTF Pin
Paul Cookson17-Feb-06 22:33
MemberPaul Cookson17-Feb-06 22:33 
GeneralRe: Restoring links in the RTF Pin
erking19-Feb-06 21:52
Membererking19-Feb-06 21:52 
GeneralRe: Restoring links in the RTF Pin
Paul Cookson21-Feb-06 22:18
MemberPaul Cookson21-Feb-06 22:18 
GeneralRe: Restoring links in the RTF Pin
SaschaBaumgart6-Mar-06 5:20
MemberSaschaBaumgart6-Mar-06 5:20 
GeneralRe: Restoring links in the RTF Pin
Benny Raymond29-Sep-06 11:36
MemberBenny Raymond29-Sep-06 11:36 
GeneralRe: Restoring links in the RTF Pin
itshibu200627-Jul-09 3:34
Memberitshibu200627-Jul-09 3:34 
GeneralLink lost when minimize to systray Pin
Labero25-Aug-05 11:31
MemberLabero25-Aug-05 11:31 
AnswerRe: Link lost when minimize to systray Pin
mav.northwind25-Aug-05 20:22
Membermav.northwind25-Aug-05 20:22 
GeneralClear all text Pin
Labero24-Aug-05 19:18
MemberLabero24-Aug-05 19:18 
GeneralRe: Clear all text Pin
mav.northwind24-Aug-05 19:49
Membermav.northwind24-Aug-05 19:49 

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.