TextBox最大字符数(不是MaxLength)

我正在使用System.Windows.Forms.TextBox 。 根据文档, MaxLength属性控制输入用户可以键入或粘贴到TextBox中的字符数量(即,可以通过使用例如AppendText函数或Text属性以编程方式添加更多Text )。 可以从TextLength属性获取当前字符TextLength

  1. 有没有办法设置最大字符数而不制作自定义限制器,当达到自定义限制时调用Clear()
  2. 无论如何,它可以容纳的绝对最大值是多少? 它只受记忆限制吗?
  3. 达到最大值/内存满时会发生什么? 崩溃? 顶部x行被清除?
  4. 手动清除前x行的最佳方法是什么? 子串操作?

编辑:我已经测试过它可以容纳超过600k个字符,无论MaxLength如何,此时我手动停止了程序并询问了这个问题。

  1. 当然。 在派生类中覆盖/ AppendTextText 。 见下面的代码。
  2. Text属性的支持字段是一个普通的旧字符串(私有字段System.Windows.Forms.Control::text )。 因此,最大长度是字符串的最大长度,即“2 GB,或大约10亿个字符”(请参阅System.String )。
  3. 你为什么不试试看?
  4. 这取决于您的性能要求。 您可以使用Lines属性,但请注意,每次调用它时,您的整个text都将在内部解析为行。 如果你推动内容长度的限制,这将是一个坏主意。 因此,更快的方式(在执行方面,而不是编码方式)将压缩字符并计算cr / lfs。 你当然需要决定你在考虑一条线的结尾。

代码:即使在以编程方式设置文本时也强制执行MaxLength属性:

 using System; using System.Windows.Forms; namespace WindowsFormsApplication5 { class TextBoxExt : TextBox { new public void AppendText(string text) { if (this.Text.Length == this.MaxLength) { return; } else if (this.Text.Length + text.Length > this.MaxLength) { base.AppendText(text.Substring(0, (this.MaxLength - this.Text.Length))); } else { base.AppendText(text); } } public override string Text { get { return base.Text; } set { if (!string.IsNullOrEmpty(value) && value.Length > this.MaxLength) { base.Text = value.Substring(0, this.MaxLength); } else { base.Text = value; } } } // Also: Clearing top X lines with high performance public void ClearTopLines(int count) { if (count <= 0) { return; } else if (!this.Multiline) { this.Clear(); return; } string txt = this.Text; int cursor = 0, ixOf = 0, brkLength = 0, brkCount = 0; while (brkCount < count) { ixOf = txt.IndexOfBreak(cursor, out brkLength); if (ixOf < 0) { this.Clear(); return; } cursor = ixOf + brkLength; brkCount++; } this.Text = txt.Substring(cursor); } } public static class StringExt { public static int IndexOfBreak(this string str, out int length) { return IndexOfBreak(str, 0, out length); } public static int IndexOfBreak(this string str, int startIndex, out int length) { if (string.IsNullOrEmpty(str)) { length = 0; return -1; } int ub = str.Length - 1; int intchr; if (startIndex > ub) { throw new ArgumentOutOfRangeException(); } for (int i = startIndex; i <= ub; i++) { intchr = str[i]; if (intchr == 0x0D) { if (i < ub && str[i + 1] == 0x0A) { length = 2; } else { length = 1; } return i; } else if (intchr == 0x0A) { length = 1; return i; } } length = 0; return -1; } } } 

System.Windows.Forms.TextBox的Text属性是一个字符串,所以理论上它可以是字符串的最大长度

理论上的限制是一个字符串,约2GB。 但实际上,它取决于运行过程中的条件。 它等于字符串在任何给定时间可以分配的最大可用连续内存部分的大小。 我在应用程序中有一个文本框,错误大约450MB。