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

时间:2016-11-18 07:52:00

标签: c# console-application

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

我正在完成一项学校作业,其中我使用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";

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

2 个答案:

答案 0 :(得分:1)

我知道这个问题有一个公认的答案。但我会提出一个(我认为)更简单的方法来集中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);

答案 1 :(得分:0)

如果布局在彼此之上,那么您可以将第一个(if js/showDevcards (devcards/init!) (init!)) ;; what you had previously 作为参考。将第二个Button的Y坐标指定为Button 1的(Y位置+高度):

Button

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

修改

如果你想让两个按钮也在Y轴上居中,你需要向上移动第一个按钮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);

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