按钮太小两个像素

我使用Windows窗体已有很短的时间了,并且注意到按钮控件在每个方向上总是比我要制作的小1个像素。

为说明起见,将波纹管中的TextBoxesButton设置为完全相同的大小,但大小不同。

wrong size buttons 这是我用来生成按钮的代码:

public Form1() {

    InitializeComponent();

    this.Size = new Size(216,239)

    TB1 = new TextBox();
    TB1.Multiline = true;
    TB1.Size = new Size(100,100);
    TB1.Location = new Point(100,0);
    Controls.Add(TB1);

    TB2 = new TextBox();
    TB2.Multiline = true;
    TB2.Size = new Size(100,100);
    TB2.Location = new Point(0,100);
    Controls.Add(TB2);

    TestButton = new Button();
    TestButton.Text = "sdfsdf";
    TestButton.Size = new Size(100,100);
    TestButton.Location = new Point(100,100);
    Controls.Add(TestButton);

}

从图像中您可以看到按钮周围有空白。我曾尝试更改Control.MarginControl.Padding,但是按钮周围的多余空间不受这些影响。

为了使按钮显示为100x100(我想要的方式),您必须将其向上和向左移动一个像素,并使它变宽和变高两个像素。 (TextButton.Size = new Size(102,102); TextButton.Location = new Point(99,99);

我想做的是使按钮实际上达到我设置的大小。由于程序中的按钮数量众多,因此不希望手动增加每个按钮的大小,而我正在寻找一种更优雅的长期解决方案,以供日后使用。

我试图围绕名为MyButton的按钮类创建一个包装器类,但是它不适用于多态性(解释如下):

class MyButton : Button {

    public MyButton() : base() {}

    public new Size Size {

        get;
        set {
            int width = value.Width + 2; // make it two wider
            int height = value.Height + 2; // make it two taller
            Size size = new Size(width,height);
            base.Size = size;
        }
    }

    public new Point Location {

        get;
        set {
            Console.WriteLine("running"); // used to make sure this is actually being run
            int x = value.X - 1; // move it one left
            int y = value.Y - 1; // move it one up
            Point point = new Point(x,y);
            base.Location = point;
        }
    }
}

当我创建一个MyButton对象并使用myButtonObject.Size = ...时,它可以完美工作,并且可以确定按钮的大小和位置。但是,在我的代码的另一个地方,我有一个函数,该函数接受一个Control对象作为输入,并且这里的MyButton类代码没有被使用。

MyButton btn1 = new MyButton();
btn1.Size = new Size(100,100);
btn.Location = new Point(100,100);
// ^ this works great and the button is the right size

public void ControlFormatter(Control control) {
    control.Size = new Size(100,100);
    control.Location = new Point(100,100);
}

MyButton btn2 = new MyButton();
ControlFormatter(btn2);
// ^ this doesn't work

使用我在Console.WriteLine("running")中输入的MyButton.Location.Set打印语句,我可以知道当在control.Location中调用ControlFormatter()时,我编写的代码未运行(我只能假设它使用默认的Control.Location属性,从而使按钮的尺寸错误。

我想我要问两件事

  1. 是否有更简便/更好/更清洁的方法来使按钮的大小合适?
  2. 如何使ControlFormatter()在不能使用MyButton.Size时使用Control.Size

谢谢,我也是C#的新手,所以很感谢恩典。

wjqact 回答:按钮太小两个像素

我选择了更快,更脏的方法来测试ControlFormatter()函数中的Control是否为Button。

public void ControlFormatter(Control control) {
    int width = 100;
    int height = 100;

    if (control is Button) {
        width -= 2;
        height -= 2;
    }

    control.Size = new Size(width,height);
    control.Position = new Point(); // you get the jist
}
本文链接:https://www.f2er.com/3112589.html

大家都在问