Suppose you have a form called FormBase and all other forms inherit from this form.
For example, I have public class Form formTest : FormBase
What I have now in the ctor of formTest:
public class Form formTest : FormBase
{
public formTest()
{
InitializeComponent();
Program.MainForm.AddToFormSizes(this, this.Size);
}
}
This code adds the instance of formTest to a dictionary on the mainform with its size
This works, but I would like to move this code to FormBase so I don't have to put this line of code in every inherited form.
public class Form FormBase : Form
{
public FormBase()
{
InitializeComponent();
Program.MainForm.AddToFormSizes(this, this.Size);
}
}
Now, the problem is that when I do that, size will have the size of FormBase in design-time, not the size of formTest.
Is there a way in FormBase to capture the size of formTest or any other form that inherited from FormBase?
for reference, this is the code of AddToFormSizes in the MainForm
private Dictionary<Form, Size> _formSizes = new Dictionary<Form, Size>();
public void AddToFormSizes(Form form, Size size)
{
_formSizes.Add(form, form.Size);
}
Problem:
Using a
Formas base for other Forms, in the base class constructor, thethisreference returns theSizeof the base class instead of theSizeof the derived class.It's just a matter of following the sequence of events:
Given the constructor of a Form derived from
FormBase:when the class is first created:
the constructor of the base class (
FormBase) is called first.At this point, the
thisreference is set toFormDerived, but all the properties, including theNameand the Form's Caption (Text), are set to the values of the base class.Hence, calling a method that uses
thisin the base class constructor:this.Sizewill return the Size of the base class, not the derived class.The
FormDerivedconstructor is called next. At this point, all the properties defined in theInitializeComponent()method will be set.If the
AddToFormSizes()method is moved to the derived class constructor,thiswill reference the expected values. But, the static method call must be inserted in each derived class ofFormBase.The
AddToFormSizes()method can be instead moved to and called from the overriddenOnHandleCreated()method of the base class, which will be called when the derived Form is first shown:will cause a call to
FormBase.OnHandleCreated().At this point, the
thisreference is already set to the derived class and all the properties defined inInitializeComponent()will be already set to the values of the derived class.Name,TextandSizeincluded, of course.Here,
thisisFormDerivedwith all the properties set in its constructor: