1. Set a button to be centered on the Panel
this.btnExit.Location = new System.Drawing.Point(pnlButton.Width / 2, pnlButton.Height / 2);
2. Automatically sort multiple buttons on the Panel
Original state:
Code for adjusting the order:
/// <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; } }
Preliminary adjustment appearance:
Note that the button order is reversed!
So how to make the button order correct?
The code is as follows:
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 }
The effect at this time is as follows:
Expansion: Click to open the link
The above is the content of the Winform Panel button location. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!