Disable selecting text in a TextBox

2020-02-01 08:18发布

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

9条回答
放我归山
2楼-- · 2020-02-01 08:43

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;
}
查看更多
等我变得足够好
3楼-- · 2020-02-01 08:47
private void textBox5_Click(object sender, EventArgs e)
{
    this.textBox5.SelectionStart = this.textBox5.Text.Length;
}
查看更多
Summer. ? 凉城
4楼-- · 2020-02-01 08:48

In WinForms, the correct method is to assign the event MouseMove and set the SelectionLength to 0.

I´ve tried here and works perfectly.

查看更多
5楼-- · 2020-02-01 08:51

If you are using XAML / WPF you should use a TextBlock instead of a TextBox.

ONLY IF YOU USE A TEXTBOX AS A DISPLAY AND NOT FOR INPUT - as TextBlock makes it seem as if the text is "engraved" onto the form itself, and not within a textbox. To get a Border around the TextBlock (if you wish), you can either do it :

In XAML such as :

<Border BorderThickness="1" BorderBrush="Gray">
    <TextBlock Background="White" Text="Your Own TextBlock"/>
</Border>

Or dynamically in C# Code:

//Create a Border object
Border border = new Border();
border.BorderThickness = new Thickness(1);
border.BorderBrush = Brushes.Black;

//Create the TextBlock object           
TextBlock tb = new TextBlock();
tb.Background = Brushes.White;
tb.Text = "Your Own TextBlock";

//Make the text block a child to the border
border.Child = tb;
查看更多
混吃等死
6楼-- · 2020-02-01 08:52

I came across of this thread for my same issue I faced. Somehow I resolved it as below,

if (sender != null)
                {
                    e.Handled = true;
                    if((sender as TextBox).SelectionLength != 0)
                        (sender as TextBox).SelectionLength = 0;
                }

Verifying if the length changed other than 0, then only set it to 0, resolves the recursive loop.

查看更多
ら.Afraid
7楼-- · 2020-02-01 08:57

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;
查看更多
登录 后发表回答