Vitalii Paprotskyi
Vitalii Paprotskyi

Reputation: 389

Is there selection text event in text box

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.

Upvotes: 6

Views: 3317

Answers (2)

Adriano Repetti
Adriano Repetti

Reputation: 67080

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).

Upvotes: 7

Ian
Ian

Reputation: 30813

If you use RichTextBox, there is a property called SelectedText. You can check if the SelectedText is not empty:

if (richTextBox1.SelectedText.Length > 0){ //means there is a selection
}

Combine it with SelectionChanged event:

private void richTextBox1_SelectionChanged(object sender, EventArgs e) {
    bool enabled = richTextBox1.SelectedText.Length > 0;
    //do something
}

You could control to enable/disable your Control when there is/isn't selected text.

Upvotes: 3

Related Questions