Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all I started working on WPF richtextbox and it seems that it does not have features like auto detect url as in windows richtextbox. I need help in detecting hyperlink when we paste data in the richtextbox (wpf) .I already found some code blocks which works fine with typed words like I type www.google.com and when I press space or enter key after "m" in "www.google.com" it will traverse back and check for the previous space or enter and detect hyperlink and make it hyperlink.

I used following code to work with
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/d3b82728-2b16-4b53-9550-e1cc5c39b169[^]

It works fine most of the time but my problem is it goes to the link after traversing every character and when I have a lot of data it is not a better solution. Also it does not work with multiple paragraphs.

I tried another option to jump directly to the link word and detect it and make it hyperlink using following function

here match is a match collection which contains all the matches of urls
here I used following regex value
"(?<=\w{1})?(((ht|f)tp(s?))\://)?(www.[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&amp;%\$#\=~_\-]+))*"

GetPositionAtOffset(match.index, LogicalDirection.Forward)

and get the point
But I get the following errors :

1) Hyperlink can not exists in the boundry of other ( can be caught in catch block so not a big problem)

Can anyone please help me in detecting urls when we paste text in it.




2 )Error code 0x80131623 ( can be found details when googled) and really challanging for me.


( I really apologize for grammatical or English mistakes)
Thanks
Posted

Maybe some help in here...

Auto-detecting Hyperlinks in RichTextBox - Part I[^]
Auto-detecting Hyperlinks in RichTextBox - Part II[^]


*Edit* Or maybe not...looks like you need regex help, not a way to detect URLs... :)
 
Share this answer
 
v2
Comments
Tarun.K.S 15-Jul-11 13:46pm    
Nice link. Bookmarked for future reference! 5+
I've been struggling with this problem, off and on, for several months. Today, I decided to ask Bing Chat how to do this. I gave Bing the following direction: write c# code to extend the .net RichTextBox control in a WPF application so that urls are clickable.

Bing provided the following solution...

-----------------------------------------------------------------------------

To extend the .NET RichTextBox control in a WPF application using C# to make URLs clickable, you can use the TextPointer class to find the start and end positions of the URLs in the text. Here’s an example of how to create an extension method for the RichTextBox control:
C#
public static class RichTextBoxExtensions
{
    public static void MakeUrlsClickable(this RichTextBox self)
    {
        TextPointer pointer = self.Document.ContentStart;
        while (pointer != null)
        {
            if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
            {
                string textRun = pointer.GetTextInRun(LogicalDirection.Forward);
                MatchCollection matches = Regex.Matches(textRun, @"(https?://[^\s]+)");
                foreach (Match match in matches)
                {
                    TextPointer start = pointer.GetPositionAtOffset(match.Index);
                    TextPointer end = start.GetPositionAtOffset(match.Length);
                    Hyperlink hyperlink = new Hyperlink(start, end);
                    hyperlink.NavigateUri = new Uri(match.Value);
                }
            }
            pointer = pointer.GetNextContextPosition(LogicalDirection.Forward);
        }
    }
}

You can then use this method on any RichTextBox control in your WPF application. For example, if you have a RichTextBox control named myRichTextBox, you can call the MakeUrlsClickable extension method like this:
C#
myRichTextBox.MakeUrlsClickable();


-----------------------------------------------------------------------------

This answer got me 80% to a solution. In addition to that code, you have to add a setter properly in the XAML code, plus some code behind for that setter.

So, after fiddling with Bing's code, here's what I finally implemented...

-----------------------------------------------------------------------------

In the XAML code:
XAML
<RichTextBox>
    <RichTextBox.Resources>
        <Style TargetType="Hyperlink">
            <Setter Property="Cursor" Value="Hand" />
            <EventSetter Event="MouseLeftButtonDown" Handler="Hyperlink_MouseLeftButtonDown" />
        </Style>
    </RichTextBox.Resources>
</RichTextBox>

In the code behind:
C#
private void Hyperlink_MouseLeftButtonDown(object sender, MouseEventArgs e)
        {
            var hyperlink = (Hyperlink)sender;
            Process.Start(new ProcessStartInfo(hyperlink.NavigateUri.ToString())
            {
                UseShellExecute = true,
            });
            e.Handled = true;
        }

The extension to the RichTextBox control:
C#
namespace RichTextBoxExtensions
{
    public static class RichTextBoxExtensions
    {
        /// <summary>
        /// Scan the content of a RichTextBox control and make any https URLs
        /// clickable.  The initial version of this method was written by Bing Chat,
        /// and then tidied up by me and Intellicode.
        /// </summary>
        /// <param name="self"></param>
        public static void MakeUrlsClickable(this RichTextBox self)
        {
            TextPointer pointer = self.Document.ContentStart;
            while (pointer != null)
            {
                if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    string textRun = pointer.GetTextInRun(LogicalDirection.Forward);
                    MatchCollection matches = Regex.Matches(textRun, @"(https?://[^\s]+)");
                    foreach (Match match in matches.Cast<Match>())
                    {
                        TextPointer start = pointer.GetPositionAtOffset(match.Index);
                        TextPointer end = start.GetPositionAtOffset(match.Length);
                        Hyperlink hyperlink = new(start, end)
                        {
                            NavigateUri = new Uri(match.Value)
                        };
                    }
                }
                pointer = pointer.GetNextContextPosition(LogicalDirection.Forward);
            }
        }
}

If you have a RichTextBox control named myRichTextBox, you can call the MakeUrlsClickable extension method like this:
C#
myRichTextBox.MakeUrlsClickable();
 
Share this answer
 
I think you just need to make sure that the detecturl property of the richtextbox is set to true.

Look at the following link

http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.detecturls.aspx[^]

Hope this is helpful.

--
AJ
 
Share this answer
 
Comments
Tarun.K.S 15-Jul-11 13:45pm    
Nice link. 5+
ankitjoshi24 15-Jul-11 14:01pm    
thank you :-)
deveoper12345 18-Jul-11 5:26am    
Hi thanks but it is windows control property not of wpf richtextbox

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900