Use parameter passed to form constructor in CreateParams in WinForms.NET

2k Views Asked by At

I have a custom form defined like this:

internal class DropDownForm : System.Windows.Forms.Form
{
    public DropDownForm(bool needShadow)
    { ... }
}

I need to enable form shadow depending on the needShadow parameter passed to the form constructor in the overridden CreateParams member - something like this:

protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;

        if (needShadow)
            cp.ClassStyle |= CS_DROPSHADOW;

        return cp;
    }
}

The problem is that I can't access the needShadow parameter passed to the form constructor in this CreateParams. The CreateParams member is executed before the first statement in my custom form constructor, and I can't cache the needShadow value passed to the form constructor in a form field to use it later in CreateParams.

To solve the problem, I could turn this needShadow parameter into a static property of my form, set it before form creation and use this value in the overridden CreateParams. But obviously it is not a good way as my app can create several instances of this form, each with its own needShadow value.

Is there a neat solution to this problem in WinForms .NET?

1

There are 1 best solutions below

0
On BEST ANSWER

Well, CreateParams will be called several times. First time call will be by Form() constructor without even Handle creation and that's why you can safely ignore it:

public partial class DropDownForm : Form { 
  private needShadow = false;

  public DropDownForm(bool needShadow) {
    this.needShadow = needShadow;

    // Actually, you should have needShadow set before this call
    InitializeComponent();
  }

  protected override CreateParams CreateParams {
    get {
      CreateParams cp = base.CreateParams;

      if (needShadow)
        cp.ClassStyle |= CS_DROPSHADOW;

      return cp;
   }
 }
 ...