Winform窗体的居中,两者不是父子关系

本文介绍了两种在软件开发中实现窗体居中显示的方法:构造函数法和封装方法。构造函数法通过在窗体加载事件中计算位置,使窗体在父窗体中居中。封装方法则通过创建一个包含全局变量的类来共享位置信息,实现窗体的居中显示。封装方法因其实现的简便性而更为推荐。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

比如: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);
}
}
由上可得方法二更方便。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值