RichTextBox get full word after clicking on it with the mouse

How to get the whole word on click? I know that similar questions have already been and I looked, but for some reason there are strange and very old solutions for 40 lines of code. Maybe there is something more modern?

Upvotes: 0

Views: 537

Answers (2)

Victor
Victor

Reputation: 8915

The code below demonstrates how to get a word on the current caret position in the RichTextBox control.

The XAML:

<Window ... >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <RichTextBox Grid.Row="0" x:Name="rtb" AllowDrop="True" VerticalScrollBarVisibility="Auto" Padding="2"
                    PreviewMouseUp="rtb_PreviewMouseUp" >
            <FlowDocument>
                <Paragraph FontSize="18" TextAlignment="Left" >

                   <!-- The RichTextBox control content should defined be here
                        or use the PASTE command to add some content... -->

                </Paragraph>
            </FlowDocument>
        </RichTextBox> 
        <Button Grid.Row="2" Click="Button_Click">Mark Current Word</Button>                   
    </Grid>
</Window>

The function below gets a pointer to the position from which the text is parsed in the specified direction to detect a word boundary. The pattern variable defines set of possible a word delimiters.

public static class TextPointerExt
{
    public static TextPointer GetEdgeTextPointer(this TextPointer position, LogicalDirection direction)
    {
        string pattern = @" ,;.!""?"; // Delimiters 
        int step = direction == LogicalDirection.Forward ? 1 : -1;    
        for (; position != null;)
        {
            var text = position.GetTextInRun(direction);    
            int offset = 0;
            int i = direction == LogicalDirection.Forward ? 0 : text.Length - 1;

            for (; i >= 0 && i < text.Length; offset++, i += step)
            {
                if (pattern.Contains(text[i]))
                {
                    return position.GetPositionAtOffset(offset * step, LogicalDirection.Forward);
                }
            }

            position = position.GetPositionAtOffset(offset * step, LogicalDirection.Forward);
            for (TextPointer latest = position; ;)
            {
                if ((position = position.GetNextContextPosition(direction)) == null)
                    return latest;

                var context = position.GetPointerContext(direction);
                var adjacent = position.GetAdjacentElement(direction);    
                if (context == TextPointerContext.Text)
                {
                    if (position.GetTextInRun(direction).Length > 0)
                        break;
                }
                else if (context == TextPointerContext.ElementStart && adjacent is Paragraph)
                {
                    return latest;
                }
            }
        }
        return position;
    }
}

Example of using the GetEdgeTextPointer() method to determine the current pointed word:

public void GetCurrentWord()
{          
    TextPointer current = rtb.CaretPosition;
    var start = current.GetEdgeTextPointer(LogicalDirection.Backward); // Word position before caret
    var end = current.GetEdgeTextPointer(LogicalDirection.Forward); // Word position after caret

    if (start is TextPointer && end is TextPointer && start.CompareTo(end) != 0)
    {
        TextRange textrange = new TextRange(start, end);
        // Print the found word to the debug window.
        System.Diagnostics.Debug.WriteLine(textrange.Text);

        // Select the found word
        rtb.Selection.Select(start, end);
    }
    rtb.Focus();
}

private void rtb_PreviewMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    GetCurrentWord();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    GetCurrentWord();
}

Upvotes: 1

persian-theme
persian-theme

Reputation: 6638

Use event PreviewMouseDown to select the whole word. Of course, depending on the function you want, you can use similar events

private void richTextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    TextSelection ts = richTextBox.Selection;
    string text = ts.Text;
    if (!string.IsNullOrEmpty(text))
        MessageBox.Show(text);
}

Upvotes: 0

Related Questions