I have a textbox with the following (important) properties:
this.license.Multiline = true;
this.license.ReadOnly = true;
this.license.ScrollBars = System.Win
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);
}
}
In WinForms, the correct method is to assign the event MouseMove and set the SelectionLength to 0.
I´ve tried here and works perfectly.
Since the standard TextBox doesn't have the SelectionChanged event, here's what I came up with.
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
TextBox1.SelectionLength = 0;
}
You can use a disabled RichTextBox
and reset the color to black afterwards.
RichTextBox rtb = new RichTextBox();
rtb.IsEnabled = false;
rtb.Text = "something";
rtb.SelectAll();
rtb.SelectionColor = Color.Black;
rtb.SelectedText = String.Empty;