I have a project that has forms that inherit properties from a base form (called frmBase). I have run into an issue that is really confusing me:
I want the program to center on the user screen, so I added
this.CenterToScreen();
to frmBase_Load(). That works great when I run the app, BUT, when I try to design any of the forms that inherit from frmBase, they all get moved to the very bottom right corner of the designer screen and I have to use scrollbars to see them.
If I move the
this.CenterToScreen();
to the frmBase() code, the app defaults to the top-left of the screen when it runs, but the designer displays the form correctly for me. Any idea what is going on? I searched, but can't seem to find a similar question, although I know I can't be the first person this has happened to. . . . .
As indicated by Hans and Reza your base class is being instantiated by the Visual Studio Form Designer so the code in the constructor and its Load event run as well. See this great answer for a detailed explanation of the parse behavior of the designer. Using the property DesignMode
you can either prevent code being executed or make a distinction. The following code sample demonstrates its use:
The baseform sets the background color to Red when in DesignMode and Green when not in DesignMode.
// Form1 inherits from this class
public class MyBase : Form
{
public MyBase()
{
// hookup load event
this.Load += (s, e) =>
{
// check in which state we are
if (this.DesignMode)
{
this.BackColor = Color.Red;
}
else
{
this.BackColor = Color.Green;
}
};
}
}
No magic in the code, but notice the use of MyBase
instead of Form
// we inherit from MyBase!
public partial class Form1 : MyBase
{
public Form1()
{
InitializeComponent();
}
}
Leading to the following result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With