Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable selecting text in a TextBox

I have a textbox with the following (important) properties:

this.license.Multiline = true;
this.license.ReadOnly = true;
this.license.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.license.ShortcutsEnabled = false;

It looks like this:

Textbox with highlighted text in it

How can I disable the user to highlight text in this textbox (I do not want to disable the textbox completely)?

like image 789
Victor Avatar asked Nov 06 '12 18:11

Victor


2 Answers

Attach to the SelectionChanged event, and inside the event set e.Handled = true; and the SelectionLength = 0; and that will stop the selection from occuring. This is similar to what it takes to keep a key press from happening.

like image 108
Mike Perrenoud Avatar answered Sep 23 '22 14:09

Mike Perrenoud


To disable selection highlight in a TextBox, you can override WndProc and handle WM_SETFOCUS message and replace it with a WM_KILLFOCUS. Please be aware that it doesn't make the TextBox control read-only and if you need to make it read-only, you should also set ReadOnly property to true. If you set ReadOnly to true, you can set and its BackColor to White or any other suitable color which you want.

In below code, I added a SelectionHighlightEnabled property to MyTextBox to make enabling or disabling the selection highlight easy:

  • SelectionHighlightEnabled: Gets or sets a value indicating selection highlight is enabled or not. The value is true by default to act like a normal TextBox. If you set it to false then the selection highlight will not be rendered.
using System.ComponentModel;
using System.Windows.Forms;
public class MyTextBox : TextBox
{
    public MyTextBox()
    {
        SelectionHighlightEnabled = true;
    }
    const int WM_SETFOCUS = 0x0007;
    const int WM_KILLFOCUS = 0x0008;
    [DefaultValue(true)]
    public bool SelectionHighlightEnabled { get; set; }
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_SETFOCUS && !SelectionHighlightEnabled)
            m.Msg = WM_KILLFOCUS;

        base.WndProc(ref m);
    }
}
like image 38
Reza Aghaei Avatar answered Sep 25 '22 14:09

Reza Aghaei