'How to check if some text in a RichTextBox is selected

I am creating a text editor and I want to add copy, paste and cut functions in the Edit Menu. I want these MenuItems to only to be enabled when there's an active selection.

I have a function that searches and highlights but there doesn't seem to be a trigger to check for in order to do it.



Solution 1:[1]

The RichTextBox.SelectionChanged event (documentation) fires when the selection of text within the control has changed.

The RichTextBox.SelectionLength property (documentation) will return the number of characters selected in control.

Handle the SelectionChanged event and set the Enabled property of the menu items based on if the SelectionLength is greater than 0:

Private Sub MyRichTextBox_SelectionChanged(sender as Object, e as EventArgs) Handles MyRichTextBox.SelectionChanged
    MyMenuItem1.Enabled = MyRichTextBox.SelectionLength > 0
    MyMenuItem2.Enabled = MyMenuItem1.Enabled
    MyMenuItem3.Enabled = MyMenuItem1.Enabled
End Sub

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1