无法将AutoSize属性设置为动态创建的TextBox C#VS 2017

问题描述 投票:0回答:1

我正在运行时创建TextBoxes,需要它们具有固定的宽度。但是,正如我期望的那样,用户可能会输入一些大字,因此它应该是多行的,因此会增加其高度。

我已经能够设置除AutoSize以外的所有类型的属性,我相信我必须这样做,因为我的TextBox行为不如我希望的那样。当我键入较大的输入内容时,它们会将所有内容仅保留在一行中,并且由于其长度固定,因此不会显示整个文本。

C#不允许我执行textbox1.Autosize = True;

这是我到目前为止的内容:

   TextBox textBox1 = new TextBox()
    {
        Name = i.ToString() + j.ToString() + "a",
        Text = "",
        Location = new System.Drawing.Point(xCoord + 2, yCoord + 10),
        TextAlign = HorizontalAlignment.Left,
        Font = new Font("ArialNarrow", 10),
        Width = 30,
        Enabled = true,
        BorderStyle = BorderStyle.None,
        Multiline = true,
        WordWrap = true,
        TabIndex = tabIndex + 1
    };

如何将Autosize属性设置为动态创建的TextBox?

或者还有另一种方法可以完成我想做的事情?

c# visual-studio textbox autosize
1个回答
0
投票

您可以尝试使用以下代码来创建预期的文本框。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private const int EM_GETLINECOUNT = 0xba;
    [DllImport("user32", EntryPoint = "SendMessageA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);
    TextBox textBox1 = new TextBox()
    {
        Name = "a",
        Text = "",
        Location = new System.Drawing.Point(2, 10),
        TextAlign = HorizontalAlignment.Left,
        Font = new Font("ArialNarrow", 10),
        Width = 100,
        Enabled = true,
        BorderStyle = BorderStyle.None,
        Multiline = true,
        WordWrap = true,
    };
    private void Form1_Load(object sender, EventArgs e)
    {
        textBox1.TextChanged += TextBox1_TextChanged;
        this.Controls.Add(textBox1);
    }

    private void TextBox1_TextChanged(object sender, EventArgs e)
    {
        var numberOfLines = SendMessage(textBox1.Handle.ToInt32(), EM_GETLINECOUNT, 0, 0);
        textBox1.Height = (textBox1.Font.Height + 2) * numberOfLines;
    }
}

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.