C # CenterToScreen () Winforms Designer Screen Position

I have a project that has forms that inherit properties from a base form (called frmBase). I ran into a problem that really baffled me:

I want the program focused on the user screen, so I added

this.CenterToScreen ();

in frmBase_Load (). This works fine when I run the application, BUT, when I try to create any of the forms that inherit from frmBase, they all move to the lower right corner of the designer screen, and I have to use the scroll bars to see them.

If i move

this.CenterToScreen ();

to frmBase () code, by default the application is placed in the upper left part of the screen when it starts, but the designer displays the form correctly for me. Any idea what is going on? I searched, but it seemed I could not find a similar question, although I know that I can not be the first with whom this happened. ,,

+5
source share
1 answer

As indicated by Hans and Reza , your base class is instantiated by Visual Studio Form Designer, so the code in the constructor and its loading event are also executed. See This Great Answer for a detailed explanation of designer analysis behavior . Using the DesignMode property, you can either prevent code execution or make a distinction. The following code example demonstrates its use:

Basic form

The basic form sets the background color to red when in DesignMode and green if 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; } }; } } 

Form1, which inherits the base form

There is no magic in the code, but pay attention to using MyBase instead of Form

 // we inherit from MyBase! public partial class Form1 : MyBase { public Form1() { InitializeComponent(); } } 

Following the result below:

development time and runtime in one view

+3
source

Source: https://habr.com/ru/post/1246158/


All Articles