Search code examples
c#winformsbackcolor

C# 'lock' the Form.BackColor


Basically I'm creating my own form

public class CryForm : System.Windows.Forms.Form

for several reasons, one of which is a very specific style.

Therefore I want the Form.BackColor property to be 'locked' to Black, so that it cannot be changed from 'outside'

CryForm1.BackColor = Color.whatevercolorulike

should not be possible anymore.

Is there any way to achieve this or should I come up with a completely different solution?


Solution

  • If your need to is to 'lock' the background color of the form at design-time, probably the most efficient and least error-prone solution would be to override the BackColor property and mark with an attribute, then inherit from the form in the designer.

    You could declare:

    public class FixedBackgroundForm : Form
    {
        protected new static readonly Color DefaultBackColor = Color.Black;
    
        [Browsable(false),
            DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override Color BackColor
        {
            get { return base.BackColor; }
            set { base.BackColor = value; }
        }
    
        public FixedBackgroundForm()
        {
            this.BackColor = DefaultBackColor
        }
    }
    

    Which would both set your form background color to Black automatically, and prevent changing of the background color from within the designer.

    When you add new forms to your project, inherit from FixedBackgroundForm:

    public partial class Form1 : FixedBackgroundForm
    {
        ...
    }
    

    If you needed to "fix" the background color to black no matter what, simply use this line for the BackColor setter:

    set { base.BackColor = DefaultBackColor; }