我正在使用System.Windows.Forms.TextBox.根据文档,MaxLength属性控制进入用户可以键入或粘贴到TextBox中的字符数量(即,可以通过使用例如AppendText函数或Text属性以编程方式添加更多字符).当前的字符数量可以从TextLength酒店获得.
Clear()当达到自定义限制时调用?编辑:我测试过它可以容纳超过600k个字符,无论如何MaxLength,此时我手动停止了程序并询问了这个问题.
Jos*_*nig 11
AppendText和Text派生类.见下面的代码.Text属性的支持字段是一个普通的旧字符串(私有字段System.Windows.Forms.Control::text).因此,最大长度是字符串的最大长度,即"2 GB,或大约10亿个字符"(请参阅System.String).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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46352 次 |
| 最近记录: |