c# - 无法将 AutoSize 属性设置为动态创建的 TextBox C# VS 2017
问题描述
我在运行时创建文本框并需要它们具有固定的宽度。但是,正如我期望用户的一些大输入一样,它应该是多行的,相应地增加了它的高度。
我已经能够设置各种属性,除了 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?
还是有另一种方法来完成我想要做的事情?
解决方案
您可以尝试以下代码来制作预期的文本框。
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);
private void Form1_Load(object sender, EventArgs e)
{
TextBox[,] tb = new TextBox[10, 10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
var txt = new TextBox();
tb[i, j] = txt;
tb[i, j].Name = "t";
tb[i, j].Multiline = true;
tb[i, j].WordWrap = true;
tb[i, j].TextChanged += Tb_TextChanged;
Point p = new Point(120 * i, 100 * j);
tb[i, j].Location = p;
this.Controls.Add(tb[i,j]);
}
}
}
private void Tb_TextChanged(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
var numberOfLines = SendMessage(textBox.Handle.ToInt32(), EM_GETLINECOUNT, 0, 0);
textBox.Height = (textBox.Font.Height + 2) * numberOfLines;
}
}
推荐阅读
- android - Android studio 3.4.2 unresolved reference android.os.Bundle
- lua - 单击 Gui 按钮时如何制作替换图像&
- selenium - 这是 Cucumber 中 table.raw 的当前方法
- windows - inno setup:使用 devcon 安装 MS Loopback 适配器?
- python - Pandas - 使用将 2 行合并为 1 行
- gatsby - 如何格式化代码片段
使用 Contentful 的富文本反应渲染器的标签?
- sql-server - 我无法在 where 子句中使用 case 语句来处理参数
- reactjs - 测试具有 api 调用的 redux-saga 函数
- python - 如何为正整数场设置最大值
- java - FCM 无效的主题名称。Base64 生成带有无效字符的字符串