Following the content of the link cited by @Felipe Assunção TextBox
keep the look standard when property ReadOnly
was set to true
.
Directly manipulating the events ReadOnlyChanged
and BackColorChanged
of TextBox
, the background colour of the TextBox
by activating the ReadOnly
is changed and it is also possible to add a color change criterion, see the adaptation below.
1° 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 define the variable Color atualBackColor;
type Color
, which will temporarily store the standard color of the TextBox
and the variable bool suprimiMudancaBackColor;
responsible for removing the change in the background colour of the TexBox
, both as global.
Explanation of the outcome.
The result of this solution is that the TextBox
will keep the color standard when property ReadOnly
is set for true
, however, when the user clicks on the TexBox
with the ReadOnly
active his color will change through the method Fromknowncolor class Color
using a preset color that is represented by the element Knowncolor, and when the user clicks off the TextBox
(when he loses focus) will set the color to default color again or be white.
Note:
Maybe this way will be more laborious when you have several
TextBox
, but it is more efficient.
Source: Setting a read only Textbox default Backcolor
2° solution (method mudarReadOnly
):
A second solution I worked out was to create a method to be used in the event Loard form, see below:
private void mudarReadOnly(TextBox textBox, bool readOnly)
{
Color backColorPadrao = textBox.BackColor;
textBox.ReadOnly = readOnly;
textBox.BackColor = backColorPadrao;
}
Explanation of the outcome.
It takes two parameters, one TextBox
and the option that will turn on to disable the ReadOnly
and before it makes the change of ReadOnly
it stores the default color and then resets the color of the TextBox
through the stored color and will always keep the white color of the TextBox
.
Note:
This method can be improved, but the goal is to work with several
TextBox
on a form.
This works, if you can’t understand it later I’ll come back and translate http://stackoverflow.com/questions/18039901/setting-a-read-only-textbox-default-backcolor
– Felipe Assunção
@Felipeasunción adapted the example of the link you sent me. It worked, but the color is changed when the
textbox
takes focus through the mouse, but returns to normal when it loses focus.– gato