Setting a read only Textbox default Backcolor

2019-06-17 02:27发布

问题:

I have a TextBoxwhich is set to be ReadOnly.
At some point that TextBox is being available for editing, and it's BackColor changes (It is indicating if the value is valid).
If I want To set the Texbox back to ReadOnly, the TextBox doesn't get back the original BackColor that a ReadOnly TextBox gets.
What should I do in order to get the original color again?
I realize I can set the color manually to SystemColors.Control, but is this the "Right way"?

Code Sample

This is a simple code for demonstration. If SystemColors.Control is the way to go, i will change it in the ReadOnlyChanged Event...

    private void button1_Click(object sender, EventArgs e)
    {
        //At this point this.textBox1 is ReadOnly
        this.textBox1.ReadOnly = false;
        this.textBox1.BackColor = Color.Orange;


        /*this.textBox1.BackColor = SystemColors.Control;*/ //Is this the right way?
        this.textBox1.ReadOnly = true; //Textbox remains orange...
    }

回答1:

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;
}


回答2:

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.



回答3:

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;