I\'m using C#/.NET for a Windows Forms application. I have a text box. How can I make the text box unselectable?
I don\'t want to disable the complete textbox.
@Mystere Man: You might want a text box that cannot be used all the time. For example, I allow the user to create text boxes on a canvas and drag them around. To prevent them from selecting and moving text when they are dragging I need to disallow user input, and text selection also needs to be disabled because it causes a delay which messes up my drag function. In my application the user can only edit a text box when he has double clicked on it, and must then click outside of the text box to be able to move it again.
I basically have this code (where t is a TextBox):
// Prevent text entry
t.IsReadOnly = true;
// Prevent text selection
t.Focusable = false;
This behaviour is preferable to disabling the whole control (t.Enabled = false
), since that would also stop mousedown and doubleclick events, which would stop dragging and changing from edit to drag mode from working. Not to mention that the text box would go grey.
You have a couple of options:
Label
control instead.textBox.Enabled = false
to prevent selection (see here).Probably the best way is to put a label behind it, and when you want to make the textbox disabled, hide it and show the label in its place.
In the 'Enter' event of the textbox set the ActiveControl to something else:
private void txtMyTextbox_Enter(object sender, EventArgs e)
{
ActiveControl = objMyOtherControl;
}
private void textBox1_Click(object sender, EventArgs e)
{
this.textBox1.SelectionStart = this.textBox1.Text.Length;
}
And don't forget that: read only=true