public static class Sort { #region 设置PanelControl上按钮显示位置 /// <summary> /// 设置按钮显示位置 /// </summary> /// <param name="targetPanel">需要调整按钮顺序的Panel</param> /// <param name="buttonSpace">按钮间隔</param> public static void SetButtonCenter(ScrollableControl targetPanel, int buttonSpace) { int length = 0; int maxHeight = 0; List<Control> listBtn = new List<Control>(); System.Windows.Forms.Control.ControlCollection c = targetPanel.Controls; foreach (Control btn in c) { listBtn.Add(btn); length += btn.Width + buttonSpace; if (maxHeight < btn.Height)//获取最大高度 { maxHeight = btn.Height; } } int pnlLength = targetPanel.Width; if (length > pnlLength) //本身按钮的长度总和大于了panel的长度,不调整 { return; } int startPos = ((pnlLength - length) / 2); int yPos = 0; if (maxHeight < targetPanel.Height) { yPos = (targetPanel.Height - maxHeight) / 2;//距离panel上边框的距离 } else { yPos = targetPanel.Height / 10;//距离panel上边框的距离 } int xPos = startPos; listBtn.Sort(new ButtonSort()); foreach (Control btn in listBtn) { btn.Location = new System.Drawing.Point(xPos, yPos); xPos += btn.Width + buttonSpace; } } #endregion #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; List<Control> listControl = new List<Control>(); System.Windows.Forms.Control.ControlCollection c = container.Controls; foreach (Control btn in c) { listControl.Add(btn); length += btn.Width + buttonSpace; if (maxHeight < btn.Height)//获取最大高度 { maxHeight = btn.Height; } } int pnlLength = container.Width; if (length > pnlLength) //本身按钮的长度总和大于了panel的长度,不调整 { return; } int startPos = ((pnlLength - length) / 2); int yPos = 0; if (maxHeight < container.Height) { yPos = (container.Height - maxHeight) / 2;//距离panel上边框的距离 } else { yPos = container.Height / 10;//距离panel上边框的距离 } int xPos = startPos; listControl.Sort(new ButtonSort()); foreach (Control btn in listControl) { btn.Location = new System.Drawing.Point(xPos, yPos); xPos += btn.Width + buttonSpace; } } #endregion }
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 }
Sort類別完善版本(修正傳入控制集合大小不一致,排序後文字顯示問題)