Rumah > Artikel > pembangunan bahagian belakang > Winform Panel按钮位置
1、Panel上设置某个按钮居中
this.btnExit.Location = new System.Drawing.Point(pnlButton.Width / 2, pnlButton.Height / 2);
2、Panel上多个按钮自动排序
原始状态:
调整顺序的代码:
/// <summary> /// 设置按钮显示位置 /// </summary> /// <param name="targetPanel">要设置按钮的Panel</param> /// <param name="buttonSpace">按钮之间的间隔</param> public void SetButtonCenter(Panel targetPanel, int buttonSpace) { int length = 0; List<Button> listBtn = new List<Button>(); System.Windows.Forms.Control.ControlCollection c = targetPanel.Controls; foreach (Button btn in c) { listBtn.Add(btn); length += btn.Width + buttonSpace; } int pnlLength = targetPanel.Width; if (length > pnlLength) //本身按钮的长度总和大于了panel的长度,不调整 return; int startPos = (pnlLength - length) / 2 - 10; //左缩进10个点位 int yPos = targetPanel.Height / 2; int xPos = startPos; foreach (Button btn in listBtn) { btn.Location = new System.Drawing.Point(xPos, yPos); xPos += btn.Width + buttonSpace; } }
初步调整后的样子:
注意奥亲,按钮顺序是反向的!
那么怎么让按钮顺序正确呢?
代码如下:
private void Form1_Load(object sender, EventArgs e) { SetButtonCenter(panelTest, 2); } /// <summary> /// 设置按钮显示位置 /// </summary> /// <param name="pnlButton">需要调整按钮顺序的Panel</param> /// <param name="buttonSpace">按钮间隔</param> public void SetButtonCenter(Panel targetPanel,int buttonSpace) { int length = 0; List<Button> listBtn = new List<Button>(); System.Windows.Forms.Control.ControlCollection c = targetPanel.Controls; foreach (Button btn in c) { listBtn.Add(btn); length += btn.Width + buttonSpace; } int pnlLength = targetPanel.Width; if (length > pnlLength) //本身按钮的长度总和大于了panel的长度,不调整 return; int startPos = (pnlLength - length) / 2 - 10; //左缩进10个点位 int yPos = targetPanel.Height / 2; int xPos = startPos; listBtn.Sort(new ButtonSort()); foreach (Button btn in listBtn) { btn.Location = new System.Drawing.Point(xPos, yPos); xPos += btn.Width + buttonSpace; } } public class ButtonSort : IComparer<Button> { #region IComparer<Button> Members //IComparer<T> 接口:定义类型为比较两个对象而实现的方法。 public int Compare(Button x, Button y) { if (x.TabIndex >= y.TabIndex) return 1; else return -1; } #endregion }
此时的效果如下图:
拓展:点击打开链接
以上就是Winform Panel按钮位置的内容,更多相关内容请关注PHP中文网(www.php.cn)!