C#按钮控件排序

发布时间:2018-08-20编辑:佚名阅读(1371)

public class ButtonSort : IComparer<Control>
{
    #region IComparer<Button> Members
    //IComparer<T> 接口:定义类型为比较两个对象而实现的方法。
    public int Compare(Control x, Control y)
    {
        if (x.TabIndex >= y.TabIndex)
        {
            return 1;
        }
        else
        {
            return -1;
        }
    }
    #endregion
}
public static class Sort
{
    #region 设置Control上按钮显示位置
    /// <summary>
    /// 设置按钮显示位置
    /// </summary>
    /// <param name="container">需要调整按钮顺序的容器控件</param>
    /// <param name="buttonSpace">按钮间隔</param>
    public static void SetButtonCenter(Control container, int buttonSpace)
    {
        int length = 0;
        int maxHeight = 0;
        bool controlsHeightSame = true;//控件高度是否一致
        List<Control> listControl = new List<Control>();
        Control.ControlCollection c = container.Controls;
        foreach (Control btn in c)
        {
            if (btn is Button)
            {
                listControl.Add(btn);
                length += btn.Width + buttonSpace;
                if (maxHeight < btn.Height)//获取最大高度
                {
                    maxHeight = btn.Height;
                }
            }
        }
        listControl.ForEach(control =>
        {
            if (control.Height != maxHeight)
            {
                controlsHeightSame = false;
            }
        });
        int pnlLength = container.Width;
        if (length > pnlLength) //本身按钮的长度总和大于了panel的长度,不调整
        {
            return;
        }
        int startPos = ((pnlLength - length) / 2);
        int yPos = 0;
        int xPos = startPos;
        listControl.Sort(new ButtonSort());
        //控件绘制的起点是左上角的顶点,yPos即控件的左上角顶点的y坐标
        if (controlsHeightSame)//控件高度一致
        {
            if (maxHeight < container.Height)
            {
                yPos = (container.Height - maxHeight) / 2;//距离panel上边框的距离
            }
            else
            {
                yPos = container.Height / 10;//距离panel上边框的距离
            }
            foreach (Control btn in listControl)
            {
                btn.Location = new Point(xPos, yPos);
                xPos += btn.Width + buttonSpace;
            }
        }
        else//控件大小不一致,每个控件的yPos单独计算
        {
            foreach (Control btn in listControl)
            {
                yPos = (container.Height - btn.Height) / 2;//距离panel上边框的距离
                btn.Location = new Point(xPos, yPos);
                xPos += btn.Width + buttonSpace;
            }
        }
    }
    #endregion
}


  关键字:C#按钮控件排序


鼓掌

0

正能量

0

0

呵呵

0


评论区