Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding hyperlinks to a RichTextBox

I'm trying to dynamically add some hyperlinks to a RichTextBox using WPF and C# but am not having much success. My code is summarised below:

FlowDocument doc = new FlowDocument();
richTextBox1.Document = doc;
richTextBox1.IsReadOnly = true;

Paragraph para = new Paragraph();
doc.Blocks.Add(para);

Hyperlink link = new Hyperlink();
link.IsEnabled = true;
link.Inlines.Add("Hyperlink");
link.NavigateUri = new Uri("http://www.google.co.uk");
link.Click += new RoutedEventHandler(this.link_Click);
para.Inlines.Add(link);

....

protected void link_Click(object sender, RoutedEventArgs e) {
    MessageBox.Show("Clicked link!");
}

When I run this the RichTextBox show the link but it is grey and I cannot click on it? Can someone please point out where I might be going wrong.

Thanks.

like image 932
PaulN Avatar asked Feb 14 '12 14:02

PaulN


2 Answers

The Document in a RichTextBox is disabled by default, set RichtTextBox.IsDocumentEnabled to true.

like image 128
H.B. Avatar answered Sep 23 '22 18:09

H.B.


A simple solution for reading a richTextBox text and transforming it into a link:

richTextBox.IsDocumentEnabled = true;

TextPointer t1 = richTextBox1.Document.ContentStart;
TextPointer t2 = richTextBox1.Document.ContentEnd;
TextRange tr = TextRange(t1,t2);
string URI = tr.Text;

Hyperlink link = new Hyperlink(t1, t2);

link.IsEnabled = true;
link.NavigateUri = new Uri(URI); 
link.RequestNavigate += new RequestNavigateEventHandler(link_RequestNavigate);


private void link_RequestNavigate(object sender,RequestNavigateEventArgs e)
{
    System.Diagnostics.Process.Start(e.Uri.AbsoluteUri.ToString());
}
like image 25
Rocksn17 Avatar answered Sep 24 '22 18:09

Rocksn17