Back to Devexpress

AutoCorrect Feature

windowsforms-9890-controls-and-libraries-rich-text-editor-autocorrect.md

latest10.6 KB
Original Source

AutoCorrect Feature

  • Dec 14, 2023
  • 5 minutes to read

The RichEditControl AutoCorrect feature can help you automate inserting frequently used text, auto-correcting typing errors and misspelled capitalization. You can specify the built-in options construct a custom replacement table or handle the Autocorrect event to analyze the input text and provide the necessary substitution.

Built-in Automatic Correction Options

The following members enable you to enable certain automatic correction features:

PropertyDescription
AutoCorrectOptions.DetectUrlsAutomatically detects an inserted web address, a network path or email address and converts it to a hyperlink.
AutoCorrectOptions.CorrectTwoInitialCapitalsCorrects capitalization errors.
AutoCorrectOptions.ReplaceTextAsYouTypeScans for entries as you type and replaces them with the designated text or image.
AutoCorrectOptions.UseSpellCheckerSuggestionsAutomatically detects and corrects typos and misspelled word if the RichEditControl.SpellChecker property specifies a spell checker component. If the spell checker provides one suggestion, this suggestion automatically substitutes the incorrect word. Otherwise, no changes are made.

Use the richEditControl.Options.AutoCorrect notation to access the built-in autocorrect options, as shown in the code snippet below:

View Example

csharp
AutoCorrectOptions correctionOptions = richEditControl1.Options.AutoCorrect;

correctionOptions.CorrectTwoInitialCapitals = true;
correctionOptions.DetectUrls = false;
correctionOptions.ReplaceTextAsYouType = true;
correctionOptions.UseSpellCheckerSuggestions = true;
vb
Dim correctionOptions As AutoCorrectOptions = richEditControl1.Options.AutoCorrect

correctionOptions.CorrectTwoInitialCapitals = True
correctionOptions.DetectUrls = False
correctionOptions.ReplaceTextAsYouType = True
correctionOptions.UseSpellCheckerSuggestions = True

Automatic Correction Using Table Entries

The text expander functionality allows you to insert symbols, decipher abbreviations and insert images. Follow the steps below to implement the text expander:

Create a new AutoCorrectReplaceInfoCollection instance and fill it with AutoCorrectReplaceInfo entries:

View Example

csharp
private AutoCorrectReplaceInfoCollection LoadAbbrevs(string path)
{
    AutoCorrectReplaceInfoCollection coll = new AutoCorrectReplaceInfoCollection();
    string aLine = "";

    AutoCorrectReplaceInfo acrInfoIm = new AutoCorrectReplaceInfo(":-)", CreateImageFromResx("smile.png"));
    coll.Add(acrInfoIm);

    if (File.Exists(path))
    {
        StreamReader sr = new StreamReader(path);
        while (!(sr.EndOfStream))
        {
            aLine = sr.ReadLine();
            if (aLine != "START") continue;

            while (!(sr.EndOfStream))
            {
                aLine = sr.ReadLine();
                aLine = aLine.Trim();
                string[] words = aLine.Split('=');
                if (words.Length == 2)
                {
                    AutoCorrectReplaceInfo acrInfo = new AutoCorrectReplaceInfo(words[0], words[1]);
                    coll.Add(acrInfo);
                }
            }
        }
        sr.Close();
    }
    return coll;
}
vb
Private Function LoadAbbrevs(ByVal path As String) As AutoCorrectReplaceInfoCollection
    Dim coll As New AutoCorrectReplaceInfoCollection()
    Dim aLine As String = ""

    Dim acrInfoIm As New AutoCorrectReplaceInfo(":-)", CreateImageFromResx("smile.png"))
    coll.Add(acrInfoIm)

    If File.Exists(path) Then
        Dim sr As New StreamReader(path)
        Do While Not(sr.EndOfStream)
            aLine = sr.ReadLine()
            If aLine <> "START" Then
                Continue Do
            End If

            Do While Not(sr.EndOfStream)
                aLine = sr.ReadLine()
                aLine = aLine.Trim()
                Dim words() As String = aLine.Split("="c)
                If words.Length = 2 Then
                    Dim acrInfo As New AutoCorrectReplaceInfo(words(0), words(1))
                    coll.Add(acrInfo)
                End If
            Loop
        Loop
        sr.Close()
    End If
    Return coll
End Function

Call the IAutoCorrectService.SetReplaceTable method to register a created replacement list. Register the service after the RichEditControl instance is completely loaded, i.e. in the Form.Loaded event handler.

csharp
IAutoCorrectService svc = richEditControl1.GetService<IAutoCorrectService>();
if (svc != null)
    svc.SetReplaceTable(LoadAbbrevs("abbvs.txt"));
vb
Dim svc As IAutoCorrectService = richEditControl1.GetService(Of IAutoCorrectService)()
If svc IsNot Nothing Then
    svc.SetReplaceTable(LoadAbbrevs("abbvs.txt"))
End If

When you type a space, punctuation mark or carriage return (a character that typically means you have finished typing a word), AutoCorrect compares the word (or more precisely the group of characters) against its list of entries. If the word matches an entry, AutoCorrect substitutes this word with a replacement object.

In this example, the substitution is performed as shown in the animation below:

Automatic Correction Using the AutoCorrect Event

Handle the RichEditControl.AutoCorrect event to analyze the input text and provide a specific object for replacement. Use the following API (accessible using the AutoCorrectEventArgs.AutoCorrectInfo property) to perform the desired actions:

APIDescription
AutoCorrectInfo.TextGets the input string to check whether it should be replaced.
AutoCorrectInfo.IncrementStartPositionDecreases a text range being analyzed by moving its start by one position.
AutoCorrectInfo.DecrementStartPositionExtends a text range being analyzed by moving its start by one position.
AutoCorrectInfo.IncrementEndPositionExtends a text range being analyzed by moving its end by one position.
AutoCorrectInfo.DecrementEndPositionDecreases a text range being analyzed by moving its end by one position.
AutoCorrectInfo.ReplaceWithGets or sets the object used to replace the input string in the document.

The following code sample shows how to handle the RichEditControl.AutoCorrect event to replace the typed $ symbol with a picture of a dollar, and substitute the text enclosed in percent symbols with custom content.

csharp
private void richEditControl1_AutoCorrect(object sender, DevExpress.XtraRichEdit.AutoCorrectEventArgs e)
{
    AutoCorrectInfo info = e.AutoCorrectInfo;
    e.AutoCorrectInfo = null;

    if (info.Text.Length <= 0)
        return;

    //Find a dollar and the percent sign in the obtained text
    for (; ; )
    {
        if (!info.DecrementStartPosition())
            return;

        if (IsSeparator(info.Text[0]))
            return;

        if (info.Text[0] == '$')
        {
            //Replace the dollar sign with an image
            info.ReplaceWith = CreateImageFromResx("dollar_pic.png");
            e.AutoCorrectInfo = info;
            return;
        }

        if (info.Text[0] == '%')
        {
            //Replace a text between dollar signs with a custom content
            string replaceString = CalculateFunction(info.Text);
            if (!String.IsNullOrEmpty(replaceString))
            {
                info.ReplaceWith = replaceString;
                e.AutoCorrectInfo = info;
            }
            return;
        }
    }
}
vb
Private Sub richEditControl1_AutoCorrect(ByVal sender As Object, ByVal e As DevExpress.XtraRichEdit.AutoCorrectEventArgs) Handles richEditControl1.AutoCorrect
    Dim info As AutoCorrectInfo = e.AutoCorrectInfo
    e.AutoCorrectInfo = Nothing

    If info.Text.Length <= 0 Then
        Return
    End If

    ' Find a dollar and the percent sign in the obtained text
    Do
        If Not info.DecrementStartPosition() Then
            Return
        End If

        If IsSeparator(info.Text(0)) Then
            Return
        End If

        'Replace the dollar sign with an image
        If info.Text(0) = "$"c Then
            info.ReplaceWith = CreateImageFromResx("dollar_pic.png")
            e.AutoCorrectInfo = info
            Return
        End If

        'Replace a text between dollar signs with a custom content
        If info.Text(0) = "%"c Then
            Dim replaceString As String = CalculateFunction(info.Text)
            If Not String.IsNullOrEmpty(replaceString) Then
                info.ReplaceWith = replaceString
                e.AutoCorrectInfo = info
            End If
            Return
        End If
    Loop
End Sub