[英]How can I set a MaxLength of a line in a RichTextBox?
I wonder if there's anyway i can set a maximum number of characters for a line in a RichTextBox. 我想知道是否我可以为RichTextBox中的一行设置最大字符数。 I know I can set a general MaxLength for the whole Box, but not for the line itself.
我知道我可以为整个Box设置一个通用的MaxLength,但是不能为该行本身设置一个MaxLength。
I was thinking that the only solution, or at least a viable one, would be to select the line in a TextRange, count the chars and check if it's greater than the max number I manually set. 我以为唯一的解决方案,或者至少是一个可行的解决方案,将是选择TextRange中的行,计算字符数,并检查它是否大于我手动设置的最大数目。 Then, create a new line with:
然后,使用以下命令创建新行:
myRichTextBox.AppendText(Environment.NewLine);
and also set the caret position to the end of the selection with something similar to that: 并将插入符位置设置为所选内容的末尾,类似于以下内容:
myRichTextBox.CaretPosition = myRichTextBox.Selection.End;
Would that be the best approach for my problem, or is there an simpler way to do that? 那将是解决我问题的最佳方法,还是有一种更简单的方法来做到这一点?
您可以设置一个按键事件,在触发该事件时,验证按键和所需的长度,并在需要时附加Environment.NewLine。
This is a tricky one I think and his code can pretty much do the trick: 我认为这是一个棘手的问题,他的代码几乎可以解决这个问题:
private void myRichTextBox_TextChanged(object sender, EventArgs e)
{
int maxLen = 10;
int CursorIndex = myRichTextBox.SelectionStart;
var text = myRichTextBox.Text;
int startIndex = text.Substring(0, CursorIndex).LastIndexOf("\n") + 1;
int endIndex = text.IndexOf("\n", CursorIndex, text.Length - CursorIndex);
// if (startIndex < 0) startIndex = 0;
if (endIndex < 0) endIndex = text.Length;
string line = text.Substring(startIndex, endIndex - startIndex).Trim();
if (line.Length > maxLen)
{
int insertionPoint = startIndex + maxLen;
text = text.Insert(insertionPoint, "\n");
CursorIndex += (insertionPoint < CursorIndex) ? 1 : 0;
myRichTextBox.Text = text;
myRichTextBox.SelectionStart = CursorIndex;
}
}
however I think there should be a better way to do this. 但是我认为应该有更好的方法来做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.