Windows.Forms.Textbox Does not obey Readonly color if BackColor is Changed

Jaeden Ruiner 126 Reputation points
2022-06-22T16:52:49.743+00:00

For some reason, this is the code inside TextBoxBase:
public override Color BackColor {
get {
if (ShouldSerializeBackColor()) {
return base.BackColor;
}
else if (this.ReadOnly) {
return SystemColors.Control;
} else {
return SystemColors.Window;
}
}
set {
base.BackColor = value;
}
}
this means that if i ever set the BackColor for any reason, the readonly evaluation is never processed.
I need a way to stop this behavior. If the control is enabled, and not readonly, i want to color the background, blue, green, yellow, fuschia, you name it. But when readonly is set to true, or enabled is set to false, default system colors should be employed.

How can i achieve this?
Jaeden "Sifo Dyas" al'Raec Ruiner

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,841 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 48,976 Reputation points
    2022-06-22T17:55:36.673+00:00

    That code says to use the background color you set, if you had set it otherwise use the Control color if it is read only otherwise use the standard window color. So if you set the background color manually then that overwrites any standard Windows colors.

    If you want to change the behavior then you could handle the ReadOnlyChanged and/or EnabledChanged to determine when the properties are changed and then adjust the background color accordingly. This would be the best route if you are using the standard TextBox. However if you need to customize this for all your text boxes then create a derived type from TextBox and override the BackColor property to suit your needs.

       public override Color BackColor  
       {  
          get   
          {  
              if (Enabled && !ReadOnly)  
                 return _backColor;  
         
              return base.BackColor;  
          }  
          set => base.BackColor = _backColor = value;  
       }  
         
       private Color _backColor = SystemColors.Window;  
    
    0 comments No comments