Home > Software engineering >  How to check if some text in a RichTextBox is selected
How to check if some text in a RichTextBox is selected

Time:04-22

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.

CodePudding user response:

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
  • Related