组框C#中的中心元素[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我已经创建了窗口应用程序,并希望将元素放在组框中。我可以用代码执行此操作吗?

groupbox

c# center groupbox
1个回答
0
投票

此代码假定您将完全在代码中创建其他控件,而不是使用Designer。如果您使用Designer,只需删除该行

按钮=新按钮(){Text =“Button1”};

并将按钮控件的名称放在下一行。

    private void AddControlsToGroupBox()
    {
        Button button = new Button() { Text = "Button1" };
        CentreControlInGroupBox(this.groupBox1, button);
    }

    private void CentreControlInGroupBox(GroupBox theGroupBox, Control theControl)
    {
        // Find the centre point of the Group Box
        int groupBoxCentreWidth = theGroupBox.Width / 2;
        int groupBoxCentreHeight = theGroupBox.Height / 2;

        // Find the centre point of the Control to be positioned/added
        int controlCentreWidth = theControl.Width / 2;
        int controlCentreHeight = theControl.Height / 2;

        // Set the Control to be at the centre of the Group Box by
        // off-setting the Controls Left/Top from the Group Box centre
        theControl.Left = groupBoxCentreWidth - controlCentreWidth;
        theControl.Top = groupBoxCentreHeight - controlCentreHeight;

        // Set the Anchor to be None to make sure the control remains
        // centred after re-sizing of the form
        theControl.Anchor = AnchorStyles.None;

        // Add the control to the GroupBox's Controls collection to maintain 
        // the correct Parent/Child relationship
        theGroupBox.Controls.Add(theControl);            
    }

该代码还假设您只在组框中放置一个控件。如果有多个控件,我认为你不会觉得很难相应地调整样品。

© www.soinside.com 2019 - 2024. All rights reserved.