打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C#Winform控件随窗体缩放

实现步骤:

1.在窗体中放一个容器(例如:Panel),并且将容器的Dock属性设置为Fill。窗体中其他控件都放在这个容器中。

2.添加如下代码:

#region 控件缩放
double formWidth;//窗体原始宽度
double formHeight;//窗体原始高度
double scaleX;//水平缩放比例
double scaleY;//垂直缩放比例
Dictionary<string, string> controlInfo = new Dictionary<string, string>();//控件中心Left,Top,控件Width,控件Height,控件字体Size
/// <summary>
/// 获取所有原始数据
/// </summary>
private void GetAllInitInfo(Control CrlContainer)
{
    if (CrlContainer.Parent == this)
    {
        formWidth = Convert.ToDouble(CrlContainer.Width);
        formHeight = Convert.ToDouble(CrlContainer.Height);
    }
    foreach (Control item in CrlContainer.Controls)
    {
        if (item.Name.Trim() != "")
            controlInfo.Add(item.Name, (item.Left + item.Width / 2) + "," + (item.Top + item.Height / 2) + "," + item.Width + "," + item.Height + "," + item.Font.Size);
        if (item.Controls.Count > 0)
            GetAllInitInfo(item);
    }
}private void ControlsChangeInit(Control CrlContainer)
{
    scaleX = (Convert.ToDouble(CrlContainer.Width) / formWidth);
    scaleY = (Convert.ToDouble(CrlContainer.Height) / formHeight);
}
private void ControlsChange(Control CrlContainer)
{
    double[] pos = new double[5];//pos数组保存当前控件中心Left,Top,控件Width,控件Height,控件字体Size
    foreach (Control item in CrlContainer.Controls)
    {
        if (item.Name.Trim() != "")
        {
            if (item.Controls.Count > 0)
                ControlsChange(item);
            string[] strs = controlInfo[item.Name].Split(',');
            for (int j = 0; j < 5; j++)
            {
                pos[j] = Convert.ToDouble(strs[j]);
            }
            double itemWidth = pos[2] * scaleX;
            double itemHeight = pos[3] * scaleY;
            item.Left = Convert.ToInt32(pos[0] * scaleX - itemWidth / 2);
            item.Top = Convert.ToInt32(pos[1] * scaleY - itemHeight / 2);
            item.Width = Convert.ToInt32(itemWidth);
            item.Height = Convert.ToInt32(itemHeight);
            item.Font = new Font(item.Font.Name, float.Parse((pos[4] * Math.Min(scaleX, scaleY)).ToString()));
        }
    }
}

#endregion 

3.在窗体的Load事件中调用GetAllInitInfo方法,代码如下:

private void Form_Load(object sender, EventArgs e)
{
    GetAllInitInfo(this.Controls[0]);

4.在窗体的Resize事件中调用ControlsChangeInit和ControlsChange方法,代码如下:

private void Form_Resize(object sender, EventArgs e)
{
    ControlsChangeInit(this.Controls[0]);
    ControlsChange(this.Controls[0]);


注:原创,转载请指明出处。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C#中代码实现控件随窗体的自由变换
(转)VB实现控件与窗体能不能同步缩放呢?
vb窗体的控件随窗体变化自动调整大小
控件大小随窗口大小变化
Silverlight播放器(MediaElement)全屏问题
Visual Basic自适应窗体设计经验
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服