Setting a ReadOnly TextBox default BackColor
You have to set BackColor
to the look of a ReadOnly TextBox's BackColor
, that is Color.FromKnownColor(KnownColor.Control)
:
//this is the ReadOnlyChanged event handler for your textbox
private void textBox1_ReadOnlyChanged(object sender, EventArgs e){
if(textBox1.ReadOnly) textBox1.BackColor = Color.FromKnownColor(KnownColor.Control);
}
You may need a variable to store the current BackColor every time your TextBox's BackColor changes:
Color currentBackColor;
bool suppressBackColorChanged;
private void textBox1_BackColorChanged(object sender,EventArgs e){
if(suppressBackColorChanged) return;
currentBackColor = textBox1.BackColor;
}
private void textBox1_ReadOnlyChanged(object sender, EventArgs e){
suppressBackColorChanged = true;
textBox1.BackColor = textBox1.ReadOnly ? Color.FromKnownColor(KnownColor.Control) : currentBackColor;
suppressBackColorChanged = false;
}
Yes, that's fine. There's no reason you can't use the SystemColors to specify the desired color for the control. I've never heard of anything in WinForms
that would cause a control to automatically revert to its default color upon setting ReadOnly = true
.
I suppose one alternative is to create a class-level variable called textBox1OriginalColor
or something and set it in the form's Load
event. Then you know exactly what it was when the form was originally displayed, if you think someone might in the future set the text box's default background color to, say, blue in the designer or something.
I know this is an old question, but for posterity sake:
TextBox as well as many other controls rely on Color.Empty to decide whether or not to display its default color.
To set a TextBox back to the system default (irregardless of state):
textBox1.BackColor = Color.Empty;