【问题标题】:Form height and width measured differently than TextBox height表单高度和宽度的测量方式与 TextBox 高度不同
【发布时间】:2018-01-23 00:43:20
【问题描述】:

我正在使用一个函数来为一个用于制作文本框数组的类创建文本框,并且我想将网格置于表单的中心。经过一些调试,我意识到表单的高度和宽度是在与文本框的宽度和高度不同的比例上测量的。 变量值:

  • 高度 = 50
  • 宽度 = 50
  • numCols = 10
  • numRows = 10
  • vertCellOffset = 50
  • horzCellOffset = 50

    private TextBox AddNewTextBox()
    {
        SOSTextBox txtBox = new SOSTextBox();
        this.List.Add(txtBox);
        hostForm.Controls.Add(txtBox);
        txtBox.Height = height;
        txtBox.Width = width;
        float scrnWidth = hostForm.Width;
        float scrnHeight = hostForm.Height;
        txtBox.Top = (int)(((int)((Count - 1) / numCols) + 1) * vertCellOffset + (scrnHeight / 2 - ((numRows / 2 + 1) * vertCellOffset)));
        txtBox.Left = (int)((((Count - 1) % numCols) + 1) * horzCellOffset + (scrnWidth / 2 - ((numCols / 2 + 1) * horzCellOffset)));
        txtBox.ArrayLocation = new Point ((Count - 1) / numCols, (Count - 1) % numCols);
        txtBox.Tag = Count;
        txtBox.Font = new Font(txtBox.Font.FontFamily, height / 6.0f); // makes font size 1/3 of the height of textBox
        txtBox.Text = "\r\n";
        txtBox.KeyPress += new KeyPressEventHandler(KeyPressHandler);
        return txtBox;
    }
    

【问题讨论】:

  • 它们以完全相同的比例进行测量。但它们不会来自同一来源。表单的位置相对于它所在的屏幕,文本框相对于它们所在的容器。

标签: c# winforms components


【解决方案1】:

我在这里没有看到问题,但文本框和表单都以像素为单位“测量”。您需要关心的是表单 ClientSize 或 ClientRectangle(都是像素)。

如果您的表单没有自动调整大小,那么在表单加载事件中,您可以调用 SetClientSizeCore(width, height),其中宽度和高度是包含所有文本框的“框”的大小。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多