I'm creating a little text editor(just like notepad).I have a few buttons on my form(cut, delete, copy). I want them to be unable when there's no text selected and vice versa...Is there some event that happens when the text is selecting? I use text box control.
There is not such event but fortunately there are workarounds:
1) Do it by your own updating UI on Application.Idle
event (I admit this isn't best solution but it's more often than not my favorite because it's easier to implement):
Application.Idle += OnIdle;
And then:
private void OnIdle(object sender, EventArgs e) {
btnCopy.Enabled = txtEditor.SelectionLength > 0;
}
2) Derive your own class from RichTextControl
(not best solution if you have to handle huge - not just big - files) and handle EN_SELCHANGE
notification (most robust one also compatible with every IME I saw around). Proof of concept (pick proper values from MSDN and don't forget to set ENM_SELCHANGE
with EM_SETEVENTMASK
):
public class TextBoxEx : TextBox {
public event EventHandler SelectionChanged;
protected override void WndProc(ref Message m) {
base.WndProc(ref m);
if (m.Msg == WM_NOTIFY && m.lParam == EN_SELCHANGE) {
OnSelectionChanged(EventArgs.Empty);
}
}
// ...
}
You might do it but...default control already has this feature for you: it has a SelectionChanged
event.
Be careful if you also support clipboard pasting because you need to update your paste button according to clipboard content (then easier place is again in Application.Idle
). Calling CanPaste()
and similar methods on RichTextControl
may break some IMEs (see also In Idle cannot access RichTextControl or IME will not work).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With