Reputation: 87
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?
Upvotes: 0
Views: 822
Reputation: 1732
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; }
Upvotes: 2
Reputation: 117057
Another option is to add this to the form load event:
this.BackColorChanged += (s, e2) =>
{
if (this.BackColor != Color.Black)
this.BackColor = Color.Black;
};
Upvotes: 1
Reputation: 8843
This should work, although you won't get a compile time error when trying to set the property.
public override Color BackColor
{
get { return Color.Black; }
set { }
}
You can make it explicit that changing the BackColor
is not supported. It will result in a runtime exception if anything is trying to change it:
public override Color BackColor
{
get { return Color.Black; }
set { throw new NotSupportedException("CryForm doesn't support changing the BackColor"); }
}
Upvotes: 4
Reputation: 3497
Just add
public new Color BackColor
{
get { return Color.Black; }
}
to your code!
Upvotes: 0