PJW
PJW

Reputation: 5417

Custom Controls preventing standard controls from appearing in WinForms

I have created a custom Button for use in my WinForms applicationusing the followng little class

public class MyButton : Button
{
    protected override void OnPaint(PaintEventArgs e)
    {
        this.BackColor = Color.ForestGreen;
        base.OnPaint(e);
    }
}

I'm simply looking to make my application cusomizeable so that I only need change button colors (and in due course other controls) in one place, and that change is reflected throughout the whole application.

After creating the custom button using the above code I set about replacing all standard System.Windows.Forms.Buttons() with MyNamespace.MyButton(). However, whilst the new buttons all appear changed on the screen, other controls like text boxes (which I have not modified) simply are not rendered on the screen at all. However if I click and drag a window in my application then all of the missing controls suddenly appear.

I have no idea what is causing this. Can anyone advise me please.

Upvotes: 1

Views: 153

Answers (1)

LarsTech
LarsTech

Reputation: 81675

You shouldn't be "setting" the backcolor property in a paint event, that can cause a constant refreshing of the screen.

One option is to try setting the property in the constructor instead:

public class MyButton : Button
{
  public MyButton() {
    this.BackColor = Color.ForestGreen;
  }
}

In order to ignore the serialized BackColor property of the control, you can try to change your button class to something like this:

public class MyButton : Button {
  private Color myColor = Color.ForestGreen;

  public MyButton() {
    base.BackColor = myColor;
  }

  [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  public new Color BackColor {
    get { return myColor; }
    set { // do nothing 
    }
  }

}

This button control will effectively ignore the BackColor property in the designer. If you want to change the color of all of your buttons, you just have to change your myColor value in code and rebuild.

Upvotes: 3

Related Questions