The code that you have in the constructor of your Form will not run when you open it in designer, but the code that you have in constructor of the base class will run.
In fact, designer creates an instance of the base class of your form (runs constructor of the base) and deserializes the file which contains InitializeComponent
method and then add the base class and the controls to the design surface.
You can take a look at the following post: How does Windows Forms Designer work? and see an interesting example there, where the designer loads a form definition full of error, but the designer forms.
In general if you have a design-time requirement, it's better to rely on the design-time extensibility point of IDE extensibility point. But just for learning purpose, in the following piece of code, you can see how the code of the base constructor runs in design time of the derived class:
Create your base class like this:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace SampleWinApp
{
public partial class BaseForm : Form
{
public BaseForm()
{
InitializeComponent();
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
MessageBox.Show("Hello from Constructor!");
}
private void BaseForm_Load(object sender, EventArgs e)
{
if (DesignMode)
MessageBox.Show("Hello from Base_Load!");
}
}
}
Create the derived class like this:
using System;
using System.Windows.Forms;
namespace SampleWinApp
{
public partial class Form1 : BaseForm
{
public Form1()
{
InitializeComponent();
}
}
}
When you open Form1
, you will the message box from Constructor and Load event handler of the base class.
Pay attention to the difference when checking for design time, in constructor and rest of the code.