关键词搜索

源码搜索 ×
×

Winform Panel按钮位置

发布2014-03-10浏览5479次

详情内容

1、Panel上设置某个按钮居中

 this.btnExit.Location = new System.Drawing.Point(pnlButton.Width / 2, pnlButton.Height / 2);

2、Panel上多个按钮自动排序

原始状态:


调整顺序的代码:

  1. /// <summary>
  2. /// 设置按钮显示位置
  3. /// </summary>
  4. /// <param name="targetPanel">要设置按钮的Panel</param>
  5. /// <param name="buttonSpace">按钮之间的间隔</param>
  6. public void SetButtonCenter(Panel targetPanel, int buttonSpace)
  7. {
  8. int length = 0;
  9. List<Button> listBtn = new List<Button>();
  10. System.Windows.Forms.Control.ControlCollection c = targetPanel.Controls;
  11. foreach (Button btn in c)
  12. {
  13. listBtn.Add(btn);
  14. length += btn.Width + buttonSpace;
  15. }
  16. int pnlLength = targetPanel.Width;
  17. if (length > pnlLength) //本身按钮的长度总和大于了panel的长度,不调整
  18. return;
  19. int startPos = (pnlLength - length) / 2 - 10; //左缩进10个点位
  20. int yPos = targetPanel.Height / 2;
  21. int xPos = startPos;
  22. foreach (Button btn in listBtn)
  23. {
  24. btn.Location = new System.Drawing.Point(xPos, yPos);
  25. xPos += btn.Width + buttonSpace;
  26. }
  27. }

初步调整后的样子:

注意奥亲,按钮顺序是反向的!

那么怎么让按钮顺序正确呢?

代码如下:

  1. private void Form1_Load(object sender, EventArgs e)
  2. {
  3. SetButtonCenter(panelTest, 2);
  4. }
  5. /// <summary>
  6. /// 设置按钮显示位置
  7. /// </summary>
  8. /// <param name="pnlButton">需要调整按钮顺序的Panel</param>
  9. /// <param name="buttonSpace">按钮间隔</param>
  10. public void SetButtonCenter(Panel targetPanel,int buttonSpace)
  11. {
  12. int length = 0;
  13. List<Button> listBtn = new List<Button>();
  14. System.Windows.Forms.Control.ControlCollection c = targetPanel.Controls;
  15. foreach (Button btn in c)
  16. {
  17. listBtn.Add(btn);
  18. length += btn.Width + buttonSpace;
  19. }
  20. int pnlLength = targetPanel.Width;
  21. if (length > pnlLength) //本身按钮的长度总和大于了panel的长度,不调整
  22. return;
  23. int startPos = (pnlLength - length) / 2 - 10; //左缩进10个点位
  24. int yPos = targetPanel.Height / 2;
  25. int xPos = startPos;
  26. listBtn.Sort(new ButtonSort());
  27. foreach (Button btn in listBtn)
  28. {
  29. btn.Location = new System.Drawing.Point(xPos, yPos);
  30. xPos += btn.Width + buttonSpace;
  31. }
  32. }
  33. public class ButtonSort : IComparer<Button>
  34. {
  35. #region IComparer<Button> Members
  36. //IComparer<T> 接口:定义类型为比较两个对象而实现的方法。
  37. public int Compare(Button x, Button y)
  38. {
  39. if (x.TabIndex >= y.TabIndex)
  40. return 1;
  41. else
  42. return -1;
  43. }
  44. #endregion
  45. }
此时的效果如下图:



 拓展:点击打开链接

相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载