在扩展表单时,如何自动移动和调整按钮和标签的大小?

时间:2016-03-16 10:13:41

标签: c# winforms visual-studio-2015

所以我使用的是一个包含按钮和标签的表单应用程序(Picture),我想知道如何在最大化表单时使它们正确地重新调整大小。这些问题中的锚点/ /和停靠栏属性:C# form auto resize windowAutomatic resizing of the Windows Forms controls无效,因为它只展开了1个项目。

我需要它移动和调整大小而不会超出原始比例。所以就像我们说我有2个按钮在彼此之上。我希望它们始终保持在右侧,它们分别是10 * 12像素和边缘2像素。当我将原始窗口大小扩展三次时,每个按钮仍然距离边缘2个像素,但是30 * 36像素大。

3 个答案:

答案 0 :(得分:2)

您需要在表单上的每个控件上设置锚属性。请注意,如果您锚定两个相对的边,控件将被拉伸/压扁,但如果您只锚定到一侧,则控件将移动

请注意,Winforms应用程序使表单上的所有控件按比例调整大小是不正常的行为 - 您选择需要拉伸的控件(面板,树视图,图像,列表框等),然后选择标准控件(输入,按钮,下拉菜单等)应保持相同的大小但移动(即锚定到顶部和/或右侧)。

如果您正在尝试为您的应用程序执行某种“信息亭模式”,那么您通常会以较低的分辨率和/或较高的DPI运行以获得比例调整大小效果,这不需要更改您的应用程序,只要您在表单中应用了惯用的锚定样式。

答案 1 :(得分:0)

您可以将按钮等放在tableLayoutPanel中,其中包含一列和多行(您要放置的元素数)。将tableLayout的锚点设置为" top"和"底部"。然后在每行中放置一个按钮/标签。

使用百分比值定义每个行大小:

tableLayoutPanel1.RowStyles[i].SizeType = SizeType.Percent;
tableLayoutPanel1.RowStyles[i].Height = 20.0F; //=20%

最后将每个元素的锚点设置为" top"和"底部"太

答案 2 :(得分:0)

这是12个按钮(4x3)的示例代码。与按钮大小相比,它还会更改字体大小。

  1. 打开Windows窗体
  2. 创建12个按钮
  3. 使用以下代码:

    公共Form1()     {         InitializeComponent();         SetComponents();     }

    void SetComponents()
    {
        foreach (Control item in Controls)
        {
            if (item is Button)
            {
                item.Width = Size.Width / 4 - 16;
                item.Height = Size.Height / 4;
                item.Font = new Font(Font.FontFamily, item.Height / 5);
            }
    
            button1.Left = 10;
            button1.Top = 10;
    
            button2.Left = button1.Right + 10;
            button2.Top = button1.Top;
    
            button3.Left = button2.Right + 10;
            button3.Top = button2.Top;
    
            button4.Left = button3.Right + 10;
            button4.Top = button3.Top;
    
            button5.Left = button1.Left;
            button5.Top = button1.Bottom + 10;
    
            button6.Left = button5.Right + 10;
            button6.Top = button2.Bottom + 10;
    
            button7.Left = button6.Right + 10;
            button7.Top = button3.Bottom + 10;
    
            button8.Left = button7.Right + 10;
            button8.Top = button4.Bottom + 10;
    
            button9.Left = button1.Left;
            button9.Top = button5.Bottom + 10;
    
            button10.Left = button9.Right + 10;
            button10.Top = button6.Bottom + 10;
    
            button11.Left = button10.Right + 10;
            button11.Top = button7.Bottom + 10;
    
            button12.Left = button11.Right + 10;
            button12.Top = button8.Bottom + 10;
    
        }
    }
    
    private void Form1_Resize(object sender, EventArgs e)
    {
        SetComponents();
    }