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.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.