B
B
bbdddd2016-02-24 20:31:57
C++ / C#
bbdddd, 2016-02-24 20:31:57

How to organize word highlighting in RichEditBox?

It is necessary to highlight a substring in a RichEditBox document with a given color. For this I wrote a method:

private async Task ChangeTextColor(string text, Color color)
{
    string textStr;
    bool theEnd = false;
    int startTextPos = 0;
    myRichEdit.Document.GetText(TextGetOptions.None, out textStr);

    while (theEnd == false)
    {
        myRichEdit.Document.GetRange(startTextPos, textStr.Length).GetText(TextGetOptions.None, out textStr);
        var isFinded = myRichEdit.Document.GetRange(startTextPos, textStr.Length).FindText(text, textStr.Length, FindOptions.None);

        if (isFinded != 0)
        {
            string textStr2;
            textStr2 = myRichEdit.Document.Selection.Text;

            var dialog = new MessageDialog(textStr2);
            await dialog.ShowAsync();

            myRichEdit.Document.Selection.CharacterFormat.BackgroundColor = color;
            startTextPos = myRichEdit.Document.Selection.EndPosition;
            myRichEdit.Document.ApplyDisplayUpdates();
        }
        else
        {
            theEnd = true;
        }
    } 
}

The debugger shows that the substring is found and isFinded is equal to the number of characters in the found substring. That is, the fragment was found and, judging by the description of the FindText method, should be selected, but not. An empty string is returned in textStr2 and, accordingly, the color does not change. I can't figure out what the error is.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bbbddd, 2016-03-03
@bbdddd

Helped on stackoverflow:
My code didn't set the selection so myRichEdit.Document.Selection returned null. You need to use ITextRange.SetRange to set the selection and ITextRange.FindText to find a string in the selection.
For example:

private void ChangeTextColor(string text, Color color)
{
    string textStr;

    myRichEdit.Document.GetText(TextGetOptions.None, out textStr);

    var myRichEditLength = textStr.Length;

    myRichEdit.Document.Selection.SetRange(0, myRichEditLength);
    int i = 1;
    while (i > 0)
    {
        i = myRichEdit.Document.Selection.FindText(text, myRichEditLength, FindOptions.Case);

        ITextSelection selectedText = myRichEdit.Document.Selection;
        if (selectedText != null)
        {
            selectedText.CharacterFormat.BackgroundColor = color;
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question