创建了两个按钮但只能将一个按钮居中

Created two buttons but only able to center one

我已经搜索过堆栈溢出但无法得到确切的答案..

我正在做一项学校作业,其中我使用 C# 控制台应用程序而不是 windows 表单应用程序创建了两个按钮..现在我想将它们都居中,我可以将其中一个居中他们但不是两者

这就是我将第一个按钮居中的方式,但我如何才能将它们都居中?

Button btn_1 = new Button();
btn_1.Parent = this;
btn_1.Location = new Point(
    (ClientSize.Width - btn_1.Width) / 2,
    (ClientSize.Height - btn_1.Height) / 2
);
btn_1.Text = "some text";

通过这种方式,我只能将一个按钮居中,如何将它们都居中...如果我使用相同的代码,那么它们将重叠,但如何使它们恰好出现在中心

如果Layout在上面,那么可以参考第一个Button。指定第二个Button的Y坐标为Button的(Y-Position + the height) 1:

Button btn_1 = new Button();
btn_1.Parent = this;
btn_1.Location = new Point(
    (ClientSize.Width - btn_1.Width) / 2,
    (ClientSize.Height - btn_1.Height) / 2
);
btn_1.Text = "some text";

this.Controls.Add(btn_1);

Button btn_2 = new Button();
btn_2.Parent = this;

// here use the coordinates of the first button
btn_2.Location = new Point(btn_1.Location.X,
    btn_1.Location.Y + btn_1.Height  // position it below the first button
    );

btn_2.Text = "2";

this.Controls.Add(btn_2);

此代码会将第二个按钮放在第一个按钮下方。

编辑:

如果您希望两个按钮也以 Y 轴为中心,您需要将第一个按钮向上移动 1 个按钮高度单位,如下所示:

btn_1.Location = new Point(
    (ClientSize.Width - btn_1.Width) / 2,
    (ClientSize.Height - btn_1.Height * 2) / 2 // subtract 2 * the height!
);

减去 2 * 高度因为你有 2 个按钮

我知道这个问题有一个公认的答案。但我会提出一个(我认为)更简单的方法来使 2 个按钮居中。我会做的是使用面板,将按钮放在里面,然后将面板居中,如下所示:

Panel p1 = new Panel();
p1.Size = new Size(0, 0);
p1.AutoSize = true;
Button b1 = new Button();
b1.AutoSize = true;
b1.Text = "Some text";
Button b2 = new Button();
b2.AutoSize = true;

b2.Text = "Some other text";

p1.Controls.Add(b1);
p1.Controls.Add(b2);
b2.Location = new Point(b1.Left, b1.Top+b1.Height);


this.Controls.Add(p1);
p1.Location = new Point((ClientSize.Width - p1.Width) / 2,
                       (ClientSize.Height - p1.Height) / 2);