0
votes

I want to raise an event whenever the SelectedText or SelectionStart properties of a TextBox control are changed. Is there any simple way to do so that doesn't involve writing a custom TextBox control from scratch?

Obviously, one option would be having a timer check those properties for changes, but I would prefer not using any timers.

So far I have tried creating a control that inherits from TextBox and overrides the SelectedText property, but that failed. Plus, SelectionStart can't be overridden.

Yes, I am aware that the RichTextBox control has the SelectionChanged event. I need a normal TextBox, however, not a RichTextBox.

1
stackoverflow.com/questions/647963/… There is this.. from what I've seen its the only way possible to do this - Sayse
Yeah, I read that, my main issue with the RichTextBox control is the lack of precise selection control; it likes to always automatically highlight the entire word for me, even with the AutoWordSelection property set to false. stackoverflow.com/questions/3678620/… has a solution to that but I would still prefer to use an ordinary TextBox. - Andrew Sun
Your only other option then is dependant on why you need to use it.. you could look at DataBinding and bind the selectionlength property to a control? - Sayse
I was looking for a more KISS-style solution, to be honest. So there really isn't a way to implement a SelectionChanged event equivalent in the TextBox control? - Andrew Sun
Not that I know of sorry, I don't think textboxes are smart enough to do anything with their selection other than using its selection start and length - Sayse

1 Answers

0
votes

I don't know how to achieve your goal from the TextBox, but below is sample of solution that uses inheritance and custom component. SelectionChanged event will be raised after user selects some new text by the mouse.

Note, that MouseDown and MouseUp events along with SelectionStart and SelectionLength properties are public in TextBox, so you can avoid subclassing if you need.

class CustomTextBox : TextBox
{
    public event EventHandler SelectionChanged;

    private int _selectionStart;
    private int _selectionLength;

    protected override void OnMouseDown(MouseEventArgs e)
    {
        _selectionStart = SelectionStart;
        _selectionLength = SelectionLength;

        base.OnMouseDown(e);
    }

    protected override void OnMouseUp(MouseEventArgs e)
    {
        if (null != SelectionChanged && (_selectionStart != SelectionStart || _selectionLength != SelectionLength))
            SelectionChanged(this, EventArgs.Empty);

        base.OnMouseUp(e);
    }
}