比如:YangPinMoBan窗体在ShengChengMoKuai中居中
方法一、构造函数法:
ShengChengMoKuai窗体代码:
//声明变量
public int x1;
public int y1;
public int x2;
public int y2;
///
/// 窗体加载事件
///
///
///
private void ShengChengMoKuai_Load(object sender, EventArgs e)
{
x1 = Location.X;
y1 = Location.Y;
x2 = this.Width / 2;
y2 = this.Height / 2;
YangPinMoBan YangPinMoBan = new YangPinMoBan(this); //如果要用到构造函数传参需要加this
YangPinMoBan.TopMost = true;
YangPinMoBan.Show(this);
}
YangPinMoBan窗体代码:
ShengChengMoKuai ShengChengMoKuai = new ShengChengMoKuai();
public int x1;
public int y1;
public int x2;
public int y2;
public YangPinMoBan(ShengChengMoKuai ShengChengMoKuai)
{
InitializeComponent();
this.ShengChengMoKuai = ShengChengMoKuai;
x1 = ShengChengMoKuai.x1;
y1 = ShengChengMoKuai.y1;
x2 = ShengChengMoKuai.x2;
y2 = ShengChengMoKuai.y2;
}
/// <summary>
/// 加载事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void YangPinMoBan_Load(object sender, EventArgs e)
{
if (x1 == 0) //窗体放大时居中定位
{
int x = (this.Location.X);
int y = (this.Location.Y);
this.Location = new Point(x, y);
}
else //默认正常窗体时居中定位
{
int x = x1 + x2 - this.Width / 2;
int y = y1 + y2 - this.Height / 2;
this.Location = new Point(x,y);
}
}
方法二、封装方法:
写一个方法:
namespace EMCProject.Class
{
class LocationCentralizationClass
{
// public:可以在类外通过对象进行访问 private和protected:只可以在类内被访问
public static int x1, y1, x2, y2; //全局数据区的数据并不会因为函数的退出而释放空间。
}
}
ShengChengMoKuai窗体代码:
///
/// 窗体加载事件
///
///
///
private void ShengChengMoKuai_Load(object sender, EventArgs e)
{
LocationCentralizationClass.x1 = Location.X;
LocationCentralizationClass.y1 = Location.Y;
LocationCentralizationClass.x2 = this.Width / 2;
LocationCentralizationClass.y2 = this.Height / 2;
YangPinMoBan YangPinMoBan = new YangPinMoBan(); //如果要用到构造函数传参需要加this
YangPinMoBan.TopMost = true;
YangPinMoBan.Show(this);
}
YangPinMoBan窗体代码:
int x1 = LocationCentralizationClass.x1;
int y1 = LocationCentralizationClass.y1;
int x2 = LocationCentralizationClass.x2;
int y2 = LocationCentralizationClass.y2;
///
/// 加载事件
///
///
///
private void YangPinMoBan_Load(object sender, EventArgs e)
{
if (x1 == 0) //窗体放大时居中定位
{
int x = (this.Location.X);
int y = (this.Location.Y);
this.Location = new Point(x, y);
}
else //默认正常窗体时居中定位
{
int x = x1 + x2 - this.Width / 2;
int y = y1 + y2 - this.Height / 2;
this.Location = new Point(x,y);
}
}
由上可得方法二更方便。