如何将文本框中条目的长度限制为其宽度
c#:默认情况下,文本框接受n个条目,
我想将条目限制为其宽度
文本框中是否有任何属性可以通过它来实现,
您可以计算要绘制的文本的宽度,如果它超过文本框宽度,则返回。
在这里你可以找到一个很好的例子。
默认它只接受32767
个字符。
您可以在textbox property
中设置textbox property
的MaxLength
textbox property
希望您使用的是Windows窗体
假设WinForms,试试这个:
private bool textExceedsWidth; private void textBox1_KeyDown(object sender, KeyEventArgs e) { textExceedsWidth = false; if (e.KeyCode == Keys.Back) return; Size textSize = TextRenderer.MeasureText(textBox1.Text, textBox1.Font); if (textBox1.Width < textSize.Width) textExceedsWith = true; } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (textExceedsWidth) e.Handled = true; }
不,要做到这一点,你必须手动计算文本框宽度可以输入的最大字符数。恐怕。 您还必须考虑字体和字体大小
我知道这个问题有点陈旧,但任何人都认为这是乔治答案的扩展。 它适用于Ctrl + v,上下文菜单粘贴和键盘输入。
private string oldText; private void txtDescrip_KeyPress(object sender, KeyPressEventArgs e) { oldText = txtDescrip.Text; } private void txtDescrip_TextChanged(object sender, EventArgs e) { Size textSize = TextRenderer.MeasureText(txtDescrip.Text, txtDescrip.Font); if (textSize.Width > txtDescrip.Width)//better spacing txtDescrip.Width - 4 txtDescrip.Text = oldText; else oldText = txtDescrip.Text; }