Question

How do I set the font color of url in RichTextBox control

Asked by: locke_a

I have a WinForm application written in C# that has a RichTextBox (rtb) control.  The rtb has DetectUrls set to true and I handle the url fine.

When an event occurs in my application, I append text to the rtb using the AppendText method and set the font color for the "new" text that I'm appending using the SelectionColor property.  There are different colors for different events (message types), etc.  This works great except when a url is detected.  The rtb has a black background and the link is black rendering it invisible.

This application is used on a number of PC's with the same result; however, it recently came to my attention that there is one PC running the application where the links show up as white against the black background.

I don't want to use a WebBrowser control and use HTML, and I don't want to disable DetectUrls and try to format them on my own losing the ability to click them.

How do I control the font (color, face, etc) for a detected url in a RichTextBox?

public class frmMain : Form
{
   ...
   private void DisplayMessage(string newMsg, Color textColor)
   {
      ...
      int startPos = txtMessages.Text.Length;
 
      txtMessages.AppendText(newMsg);
      txtMessages.SelectionStart = startPos;
      txtMessages.SelectionLength = newMsg.Length;
      txtMessages.SelectionColor = textColor;
      txtMessages.SelectionHangingIndent = 55;
   }
}

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-28 at 09:26:24ID24690345
Tags

RichTextBox

,

c#

,

DetectUrls

,

WinForms

Topics

C# Programming Language

,

.NET

,

Microsoft Visual C#.Net

Participating Experts
2
Points
500
Comments
23

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. RichTextBox
    I have a RichTextBox coded to show many different font properties, like bold, italic, and fonts - functioning much like Word does. It works fine except for whenever you hit the 'Enter' key, the text does not retain the properties of the text right before it or even as display...
  2. VB.Net richtextbox formatting for winforms.
    Hey Experts, I'm looking for a component that will allow me to easily and solidly apply MSWord-like formatting features to a richtextbox. I need this for WinForms, NOT Web. I know there're a million of these available for asp.net web forms, but this does not help me. Thank y...
  3. add a symbol to richtextbox
    is there a way to add a symbol to a RichTextBox. I want to add a checkmark to the RichTextBox.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: BillyDvDPosted on 2009-09-22 at 13:05:12ID: 25396997

 

by: locke_aPosted on 2009-09-22 at 13:14:59ID: 25397096

I have in fact looked through that article but have not been able to apply it to my case.  

Additionally, there are a number of other readers who've posted comments to that same article stating that they were unable to control the foreground (text) color of the links.

 

by: BillyDvDPosted on 2009-09-22 at 13:17:35ID: 25397116

I have not tried this myself but you may be able to set 'DetectUrls' = false; and then search for these using regular expressions and updating the color based on a selcetion found.

 

by: locke_aPosted on 2009-09-22 at 13:40:04ID: 25397344

Right, but my I have some concern with that approach because I still want to be able to handle the user clicking the link and I'm not sure that a regular expression will accurately find more complex URLs.

 

by: DanRollinsPosted on 2009-10-11 at 19:29:43ID: 25548330

I understand your frustation -- I can't find anything that clearly describes a solution.

One possible partial workaround you may not have thought of:
Wait until you get an EN_LINK notif -- indicating that the mouse is over a link. The ENLINK structure provides a CHARRANGE, so you could (at that moment) change it's coloring. Perhaps that's better than nothing...

according to this:
   http://msdn.microsoft.com/en-us/library/bb788022(VS.85).aspx

    When Rich Edit locates a URL, it changes the URL text color, underlines the text,
    and notifies the client using EN_LINK.

so perhaps you don't need to wait for the mouse...

The fact that one PC you know of shows the links differently might be a clue. Perhaps there is some global window setting somewhere, akin to the XP viual styles. Or perhaps there is an obscure manifest setting. Sorry... just thinking aloud.

 

by: locke_aPosted on 2009-10-13 at 12:04:46ID: 25563185

Dan,

I appreciate the idea.  According to the documentation, it looks like this might lead in the right direction, however; I haven't been able to handle/hook/capture the WM_NOTIFY message.

According to MSDN:

"The parent window of the control receives this notification message through a WM_NOTIFY message".

The parent window in my case is a panel control in a splitter on a form.  The code to handle the WM_NOTIFY (that doesn't seem to be hit) is in the form.  I suspect that perhaps the panel is getting the notification and it's not bubbling up to the form.

Can you offer some insight for how I might get a handle on this event/message?  Will I need to create a custom control that extends the panel control and handles this, etc?

Your thoughts are appreciated!

 

by: DanRollinsPosted on 2009-10-13 at 14:50:21ID: 25565174

The WM_NOTIFY message goes to the direct parent window of the RE control.  In the dialog-based app I used for testing, I selected the RE control and selected Pop[erties, and clicked the Messages button -- it was listed as EN_LINK.  I added a handler for it.  In your case, I suggest using Spy++ to see where the EN_LINK messages are being sent.  Also, whn you create the RE control, you probably have an option to specify the parent window and you may be leaving it as he default -- which would normally mean that whatever object the Create() function was called.

Note, too that you need to tell the RE control to send the notifs (I assume you've done that because you mentioned that you are alreay handling EN_LINK clicks).

I do have some bad news... I verified that the notif comes ONLY when the mouse passes over the link (or is clicked on the link) -- and one other time, in a WM_SETCURSOR message, also triggered by mouse position/movements.

I could find no message at all when the text was actually transformed to or from underlined blue text.  There is not even an EN_UPDATE message that I could identify as being specifically about that change.

It looks like the RE's URL detection logic was grafted onto the control as an afterthought.

At this point,  I could suggest the somewhat ridiculous route I took in an HTML editor i worked on (see Use CHtmlEditCtrl to Create a Simple HTML Editor )  That is, occasionally extract the RTF source and look for changes and then change them back.  However, even that woun't work here:  The RTF data does not include the RFE_LINK flag and the text does not even have the underlined/blue attribute!   The link formatting is handled entriely programmatically at runtime.  If you save the RTF file, you won't be able to tell that the link was ever displayed differently from the adjacent text.

It might be possible to scan the in-memory RTF to locate text with the RFE_LINK attribute (0x00000020).  However, I think the better method would be to scan the text for any of the the lead-in sequences (http:, ftp:, etc)  listed here: http://msdn.microsoft.com/en-us/library/bb787991(VS.85).aspx  

Do the scanning on a timer, and when you find such a lead-in sequence, check to see if it has the CFE_LINK attribute, and if so, change it as desired.  I don't think that the RE control will change it back unless it detects a change (say the user adds a charater to the end of the URL string).  

That method would be impractical if you have a really long document.  In that case, you could perhaps do what I suspect that the RE control does -- I think that it triggers its logic on EN_CHANGE or EN_UPDATE and then examines the sequence of characters near the selection point.

-- Dan

 

by: locke_aPosted on 2009-10-14 at 09:31:13ID: 25572361

Dan,

My application is a managed C# app.  The code you reference appears to be C++.  I am not opposed to using an interop solution if I can get it working.

In my properties pane, I don't see EN_LINK or other such messages/events.  The event I am handling for my links is called "LinkClicked" and is I would presume a c# wrapper for the EN_LINK clicks behind the scene.

Also, in Spy++ I don't see the EN_LINK messages, I was thinking I was looking for a WM_NOTIFY, but didn't see any of those with EN_LINK either.  It could be that my RTB is not configured to send the notifs...

I've set a breakpoint and observed the RTF in the control, it does not appear to have any indication of the link.

This RTB in question is simply for displaying rich text.  If it helps in proposing solutions, this text is updated regularly with new messages, but the existing text is not modified.  Also, the text is inserted into the RTB programatically (in response to events that are raised), not via any type of direct user interaction.

I appreciate your patience and understanding!

 

by: DanRollinsPosted on 2009-10-14 at 15:49:58ID: 25575998

Are you outputing/appending lines of text to a log file?

If so, the user's random actions probably don't need to be taken into account.  As soon as you append a line of text, add a line break (that should trigger RE's built-in URL detection and cause the RE to change the formatting to give it the RFE_LINK attribute).  

So, directly after appending the line and the linebreak, look though the previous line and try forcing some color changes, only on characters that haf the RFE_LINK attribute.

In fact, if you scan each line as you output it, you will know in advance that RE will tweak it, so you need take special actions only after appending a line that contains "http:" (etc.)

 

by: DanRollinsPosted on 2009-10-14 at 19:54:11ID: 25576890


Wow.  My frame of reference in the TichText control -- not the .NET RTB.  I just spent an hour looking through the docs... There are about one zillion members, attributes, and events, but not one of them seems to be of any use.  We can't use EM_SETCHARFORMAT  to get a CHARFORMAT2 that would tell us that RFE_LINK has been set.  I just hate it when otherwise smart people think they are doing me a favor by hiding the underlying access to the control.   You might be abel to detect some stuff by adding handlers for one or more of these:

Control..::.OnNotifyMessage Method
Control..::.PreProcessControlMessage Method
Control..::.PreProcessMessage Method

But I have a different idea that may work.  I noticed that when I added BOLD to an RFE_LINK-attributed  it became bold, but also went underlined and blue.  What if you try adding various other attributes, such as SelectionProtected or perhaps strikethrough or something?  Maybe just setting SelectionBackColor would solve the problem.

To make this work, you would still need to recognize the special URL lead-in sequences just before appending the text into the control.  Save the current cursor location, insert the text (plus a space or linebreak, perhaps -- to trigger the automatic action), then set the desired attribute beginning at the saved location and extending for the length of the inserted text.
 

 

by: locke_aPosted on 2009-10-20 at 10:50:55ID: 25616647

Dan,

I apologize for not getting back more promptly.  I'm still working on this, but am having no luck picking out the links.  I really feel like we're on the right path, but am getting a bit frustrated with my inability to break through...

I am almost ready to just change to a webbrowser control and use the additional formatting options of HTML/CSS since this is strictly for output not user input.

It does seem however, that there should be a way to do this and I'd like to find an answer for future people looking for the same solution.

I'll keep you posted, and thanks!

 

by: DanRollinsPosted on 2009-10-20 at 15:03:56ID: 25619128

Are you going the route of pre-processing the output text, looking for lead-in sequences (http, ftp, etc.)?  That seems to be the most promising direction.  It's no good for a general-use RTB, it it sure seems like it would work for an on-screen logger in which all text was programmatically added, line-by-line.

 

by: locke_aPosted on 2009-10-21 at 08:29:04ID: 25624954

I guess I may not have understood that suggestion.  Are you suggesting that I "detect" the URLs myself by parsing for the "lead-in sequences" as you call them?

I would prefer to utilize the built in DetectUrls...  I have tried looking in the methods you suggested to determine if there is anything about the links (text or RTF) that the DetectUrls adds, and I can't find a way to handle them.

 

by: DanRollinsPosted on 2009-10-21 at 17:08:28ID: 25629719

You would still use the DetectUrls setting, and clicks would work normally.

The difference is that you also detect the URLs -- before inserting a line of text, then take action after the control has underlined the URL.  The action would be to select that text and add some highlighing/color-setting of your own.

The only tricky/unknown part:  
You might need to wait a while before modifying the format.  I can't be sure whether the RTB will overwrite all of the character attributes when it does its URL formatting.   It will probably only modify the forecolor and the underlining.   So, if you set, say, the background color, that might stick.

If, on the other hand, the RTB immediately resets all character attribute when it does its blue/underline thing, then you will need to give it some time... let it set the attributes, then you go back and set them to what you want...  Try it out.  If that's the case, I'll describe a possible way to handle that scenario.

-- Dan

 

by: locke_aPosted on 2009-10-28 at 09:30:13ID: 25685080

Dan,

I think I'm doing what you describe (if you look at the code snippet in the original question).  I am inserting a line of text, creating a selection and applying font formatting to that selection (which should include the link).

The problem is that even after changing the font formatting, the RTB seems to override the colors I've selected for the link within the selection.

You said you might have a way to handle this scenario?

 

by: DanRollinsPosted on 2009-10-28 at 17:38:19ID: 25689654

Watching how the RichText control works, it looks like the control is doing the URL detection as perhaps an idle-time background sort of thing.  

You are inserting th text, and then settings the color -- all in one action.... the RTB then gets a chance to undo your formatting.  

What I propose is that you allow the RTB time to do its thing, then go back and change it (I do not think it will change it back afterwards -- unless there is a user keystroke or other triggering action near the URL text (I admit I haven't tested this theory).

My try at implementing this would be along the lines of:

At the end of DisplayMessage, add logic to detect a url in newMessage.  If so, save the startpos and the length into member variables.  If not, set m_nNeedToFixStartPos variable to -1.

At the start of DisplayMessage, if m_nNeedToFixStartPos is not -1, then re-select it and re-color, using perhaps a different background color and then set m_nNeedToFixStartPos to -1 ...

Then proceed with the normal end-of-data insertion.

In otherwords, look for a "pending fixup" and handle it.  Then append the new message.  Then check to see if you need to schedule another "pending fixup"

--------
I'd normally provide code, but I'm unfamiliar with C# and have not worked with RTB.

 

by: DanRollinsPosted on 2009-10-28 at 17:42:17ID: 25689672

A variation:  If RTB changes the formatting back later, then rather than formatting the entire URL, try changing just the text after "http:" -- or look for some other quirky way to avoid having the RTB notice your change.

 

by: locke_aPosted on 2009-10-28 at 21:48:47ID: 25690742

Dan,

I hadn't thought of this approach.  It sounds like a viable option in my case because I'm not trying to specifically set the URL color to something other than my text color.  I'm just trying to keep it from matching the background color.

I am away from the project at the moment, but when I get back to the office I'll give this a try and report back.

Thanks again!

 

by: locke_aPosted on 2009-10-29 at 06:49:47ID: 25693601

Dan,

I wasn't sure what event to look for to handle this "afterward" so I added a button for testing and modified colors in the click handler for that button.

In my test, I wasn't even looking specifically for the URL patterns.  I simply made a selection from 0 to the length of the text and applied coloring to it.

In this simple test, the colors applied (background and foreground) to all the text EXCEPT the URLs.  The system default or whatever it is was still applied to the URLs.

No luck...

 

by: locke_aPosted on 2009-10-29 at 09:46:16ID: 25695594

Dan,

I updated the code to detect the lead-in sequences and to change the background color to one that has a high enough contrast with the default foreground.  I can now see my links (it looks like a highlighter on paper if you will).

This is less than ideal (I'd still like to be able to control the foreground), but it does seem like a possible interim solution.

 

by: DanRollinsPosted on 2009-10-29 at 15:24:27ID: 25698858

You can probably also add BOLD or italics or some other foreground attribute if that helps.    The whole URL highlighting is not implemented cleanly; it was clearly a patch-up operation.  I couldn't find any workaround for this anywhere on the web, so if you have even a partial solution, you ought to go with it.

 

by: locke_aPosted on 2009-11-02 at 11:38:01ID: 31621800

Thanks for your patience in dealing with this issue.  

Unfortunately we were unable to set the foreground color of the auto detected URL's.  We did however detect the links and set a background color which is acceptable in my case as the links are now visible.  I used the link provided in a post above (http://msdn.microsoft.com/en-us/library/bb787991(VS.85).aspx) to detect lead-in sequences.

I may use this partial solution, or give in and use a customized web browser control.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...