Following the content of the link quoted by @Felipe Assunção could cause TextBox
to keep the default look when ReadOnly
property was set to true
.
By directly manipulating events ReadOnlyChanged
and BackColorChanged
of TextBox
, you can prevent the background color of TextBox
by activating ReadOnly
from being changed and you can also add a change criterion of color, see the adaptation below.
1st solution (Events ReadOnlyChanged
and BackColorChanged
) :
private void textBoxExemplo_ReadOnlyChanged(object sender, EventArgs e)
{
suprimiMudancaBackColor = true;
textBoxExemplo.BackColor = textBoxExemplo.ReadOnly ? Color.FromKnownColor(KnownColor.Control) : atualBackColor;
suprimiMudancaBackColor = false;
}
private void textBoxExemplo_BackColorChanged(object sender, EventArgs e)
{
if (suprimiMudancaBackColor)
return;
atualBackColor = textBoxExemplo.BackColor;
}
It is necessary to set the variable Color atualBackColor;
of type Color
, which will temporarily store the default color of TextBox
and the variable bool suprimiMudancaBackColor;
responsible for suppressing the background color change of TexBox
, both as global.
Explanation of results.
The result of this solution is that TextBox
will keep the default color when the ReadOnly
property is set to true
, but when the user clicks TexBox
with ReadOnly
active color it will change through the FromKnownColor of the Color
class by using a predefined color that is represented by the KnownColor , and when the user clicks out of TextBox
(when he loses focus) will set the color to default color again or be white.
Note:
Perhaps this form will be more laborious when you have several
TextBox
, but it is more efficient.
Source: Setting a read only Textbox default Backcolor
2nd solution (method mudarReadOnly
) :
A second solution I've worked on is creating a method to be used in the Loard event of the form, see below:
private void mudarReadOnly(TextBox textBox, bool readOnly)
{
Color backColorPadrao = textBox.BackColor;
textBox.ReadOnly = readOnly;
textBox.BackColor = backColorPadrao;
}
Explanation of results.
It gets two parameters, a TextBox
and the option that will turn on disable the ReadOnly
and before it changes ReadOnly
it stores the default color and then resets the color of TextBox
through color stored and will always keep the white color of TextBox
.
Note:
This method can be improved, but the goal is to work with several
TextBox
in a form.