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:
How can I disable the user to highlight text in this textbox (I do not want to disable the textbox completely)?
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.
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);
}
}
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