Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you change the text color of a readonly TextBox?

Tags:

c#

I am writing a dictionary with c# and I'm using a textbox to show the definitions. Obviously, I need to set the ReadOnly property to true, but when I do that I'm unable to change the color of the text. Changing the Font however works fine. What should I do?

I'm using this code and setting the color works perfectly fine when the ReadOnly property is false, but doesn't change when it is true:

    private void button5_Click(object sender, EventArgs e)
    {
        FontDialog fd = new FontDialog();
        fd.ShowColor = true;
        if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            textBox3.Font = fd.Font;
            textBox3.ForeColor = fd.Color;
        }
    }
like image 591
Amen Avatar asked Dec 19 '13 17:12

Amen


3 Answers

The ForeColor property of a read-only TextBox is married to the BackColor property for some reason. So if you "tickle" the BackColor property, it will set the ForeColor property after that:

FontDialog fd = new FontDialog();
fd.ShowColor = true;
if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
  textBox3.Font = fd.Font;
  textBox3.BackColor = textBox3.BackColor;
  textBox3.ForeColor = fd.Color;
}
like image 122
LarsTech Avatar answered Oct 22 '22 20:10

LarsTech


Assuming the ForeColor is already set to the desired color (possibly in the designer), all that needs to be done is:

tb.BackColor = tb.BackColor;

This will magically trigger and fix the fore color. Although a comment explaining why this line of code is added is probably also needed.

like image 45
David Avatar answered Oct 22 '22 18:10

David


In VS 2017 this is not even needed.

In designer if you have set your ForeColor and BackColor as desired and want to switch ReadOnly on your TextBox to True

  • Change BackColor to any random color and compile
  • Change BackColor to your desired color and compile
like image 4
Thomas Rasmussen Avatar answered Oct 22 '22 19:10

Thomas Rasmussen