我有一个项目,其中包含从基本表单(称为frmBase)继承属性的表单。我遇到了一个令我困惑的问题:
我希望程序以用户屏幕为中心,所以我添加了
this.CenterToScreen();
到frmBase_Load()。当我运行应用程序时,这很有用,但是,当我尝试设计从frmBase继承的任何表单时,它们都被移动到设计器屏幕的右下角,我必须使用滚动条来查看它们。 / p>
如果我移动
this.CenterToScreen();
到frmBase()代码,app在运行时默认显示在屏幕的左上角,但设计师会为我正确显示表单。知道发生了什么事吗?我搜索过,但似乎找不到类似的问题,虽然我知道我不能成为第一个发生这种情况的人。 。 。 。 。
答案 0 :(得分:4)
如Hans和Reza所示,您的基类正由Visual Studio表单设计器实例化,因此构造函数中的代码及其Load事件也会运行。查看a detailed explanation of the parse behavior of the designer的这个好答案。使用属性DesignMode
可以阻止代码执行或进行区分。以下代码示例演示了它的用法:
在DesignMode中,baseform将背景颜色设置为Red,而不在DesignMode中时将底色设置为Green。
// 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;
}
};
}
}
代码中没有魔力,但请注意使用MyBase
代替Form
// we inherit from MyBase!
public partial class Form1 : MyBase
{
public Form1()
{
InitializeComponent();
}
}
导致以下结果: