Back to Devexpress

How to: Convert a Static URI to a Hyperlink

wpf-403684-controls-and-libraries-rich-text-editor-examples-text-how-to-convert-static-uri-to-hyperlink.md

latest5.7 KB
Original Source

How to: Convert a Static URI to a Hyperlink

  • Dec 24, 2021
  • 3 minutes to read

RichEditControl detects a hyperlink automatically when a user enters a URI. Use the approach described below to convert static URIs to hyperlinks in a loaded document.

Call the SubDocument.StartSearch(Regex) method within the RichEditControl.DocumentLoaded event handler to find all URIs in a loaded document. If the found text is not a hyperlink (i.e., its range cannot be found in the HyperlinkCollection), call the HyperlinkCollection.Create(DocumentRange) method convert the text range to a hyperlink.

csharp
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
using System;
using System.Text.RegularExpressions;

public partial class Form1 : Form
{
  // A regular expression to find a static URI
  private static Regex urlRegex =
      new Regex(@"(?:[a-z][\w-]+:(?:/{1,3}([^./]*:[^./]*@){0,1})|www\d{0,3}[.]|ftp[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\([^\s<>]*\))+(?:\([^\s<>]*\)|[^\s`!()\[\]{};:'"".,<>?«»“”‘’])",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));

public Form1()
{
    richEditControl1.DocumentLoaded += WordProcessor_DocumentLoaded;
    // Load a document
    richEditControl1.LoadDocument("Documents//test.docx");
}

private void richEditControl1_DocumentLoaded(object sender, EventArgs e)
{
    // Convert text to hyperlinks in a loaded document
    CreateHyperlinks();
}

  private void CreateHyperlinks()
  {
    Document document = richEditControl1.Document;

    // Start the document update
    document.BeginUpdate();
    IRegexSearchResult result;

    // Search for URIs
    result = document.StartSearch(urlRegex);

    // Iterate search results
    while (IsValidUri(result))
    {
        DocumentRange wordRange = result.CurrentResult;

        // If the search result is not a hyperlink, convert 
        // the range to a hyperlink
        if (!RangeHasHyperlink(wordRange))
        {
            Hyperlink hyperlink = document.Hyperlinks.Create(wordRange);
            // Use the found URI as the hyperlink address
            hyperlink.NavigateUri = document.GetText(hyperlink.Range);
        }
    }
    // Finalize the update
    document.EndUpdate();
  }

  private bool RangeHasHyperlink(DocumentRange documentRange)
  {
      // Check whether the search result is already a hyperlink
      foreach (Hyperlink h in richEditControl1.Document.Hyperlinks)
      {
          if (documentRange.Contains(h.Range.Start))
              return true;
      }

      return false;
  }

  // Make sure that the application won't crash if the
  // pattern-matching method execution exceeds its time-out interval 
  static bool IsValidUri(IRegexSearchResult result)
  {
     try
     {
        return result.FindNext();
     }
     catch (RegexMatchTimeoutException)
     {
        return false;
     }
  }
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
Imports System
Imports System.Text.RegularExpressions

Partial Public Class Form1
    Inherits Form

  ' A regular expression to find a static URI
  Private Shared urlRegex As New Regex("(?:[a-z][\w-]+:(?:/{1,3}([^./]*:[^./]*@){0,1})|www\d{0,3}[.]|ftp[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\([^\s<>]*\))+(?:\([^\s<>]*\)|[^\s`!()\[\]{};:'"".,<>?«»“”‘’])", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250))

Public Sub New()
    richEditControl1.DocumentLoaded += WordProcessor_DocumentLoaded
    ' Load a document
    richEditControl1.LoadDocument("Documents//test.docx")
End Sub

Private Sub richEditControl1_DocumentLoaded(ByVal sender As Object, ByVal e As EventArgs)
    ' Convert text to hyperlinks in a loaded document
    CreateHyperlinks()
End Sub

  Private Sub CreateHyperlinks()
    Dim document As Document = richEditControl1.Document

    ' Start the document update
    document.BeginUpdate()
    Dim result As IRegexSearchResult

    ' Search for URIs
    result = document.StartSearch(urlRegex)

    ' Iterate search results
    Do While IsValidUri(result)
        Dim wordRange As DocumentRange = result.CurrentResult

        ' If the search result is not a hyperlink, convert 
        ' the range to a hyperlink
        If Not RangeHasHyperlink(wordRange) Then
            Dim hyperlink As Hyperlink = document.Hyperlinks.Create(wordRange)
            ' Use the found URI as the hyperlink address
            hyperlink.NavigateUri = document.GetText(hyperlink.Range)
        End If
    Loop
    ' Finalize the update
    document.EndUpdate()
  End Sub

  Private Function RangeHasHyperlink(ByVal documentRange As DocumentRange) As Boolean
    ' Check whether the search result is already a hyperlink
    For Each h As Hyperlink In richEditControl1.Document.Hyperlinks
        If documentRange.Contains(h.Range.Start) Then
            Return True
        End If
    Next h

    Return False
  End Function

  ' Make sure that the application won't crash if the
  ' pattern-matching method execution exceeds its time-out interval 
  Private Shared Function IsValidUri(ByVal result As IRegexSearchResult) As Boolean
    Try
        Return result.FindNext()
    Catch e1 As RegexMatchTimeoutException
        Return False
    End Try
End Function
End Class