我已经创建了窗口应用程序,并希望将元素置于组框中。我可以用代码吗?
答案 0 :(得分:0)
此代码假定您将完全在代码中创建其他控件,而不是使用Designer。 如果您使用Designer,只需删除
行按钮按钮=新按钮(){文字="按钮1" };
并将按钮控件的名称放在下一行。
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);
}
代码还假设您只在组框中放置一个控件。我不认为如果有多个控件,你会发现很难相应地调整样本。