[英]Create event for WinForm usercontrol property changed
I want to raise an event whenever the SelectedText or SelectionStart
properties of a TextBox control are changed. 每当TextBox控件的SelectedText或
SelectionStart
属性更改时,我都想引发一个事件。 Is there any simple way to do so that doesn't involve writing a custom TextBox control from scratch? 有没有简单的方法可以做到,而无需从头开始编写自定义TextBox控件?
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. 到目前为止,我已经尝试创建一个从TextBox继承并覆盖SelectedText属性的控件,但是失败了。 Plus,
SelectionStart
can't be overridden. 另外,
SelectionStart
不能被覆盖。
Yes, I am aware that the RichTextBox control has the SelectionChanged
event. 是的,我知道RichTextBox控件具有
SelectionChanged
事件。 I need a normal TextBox, however, not a RichTextBox. 我需要一个普通的TextBox,但不需要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. 我不知道如何通过
TextBox
实现您的目标,但是下面是使用继承和自定义组件的解决方案示例。 SelectionChanged
event will be raised after user selects some new text by the mouse. 用户通过鼠标选择一些新文本后,将引发
SelectionChanged
事件。
Note, that MouseDown
and MouseUp
events along with SelectionStart
and SelectionLength
properties are public in TextBox
, so you can avoid subclassing if you need. 请注意,
MouseDown
和MouseUp
事件以及SelectionStart
和SelectionLength
属性在TextBox
是公共的,因此您可以根据需要避免子类化。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.