簡體   English   中英

如何在RichTextBox中設置一行的MaxLength?

[英]How can I set a MaxLength of a line in a RichTextBox?

我想知道是否我可以為RichTextBox中的一行設置最大字符數。 我知道我可以為整個Box設置一個通用的MaxLength,但是不能為該行本身設置一個MaxLength。

  • 我以為唯一的解決方案,或者至少是一個可行的解決方案,將是選擇TextRange中的行,計算字符數,並檢查它是否大於我手動設置的最大數目。 然后,使用以下命令創建新行:

     myRichTextBox.AppendText(Environment.NewLine); 

    並將插入符位置設置為所選內容的末尾,類似於以下內容:

     myRichTextBox.CaretPosition = myRichTextBox.Selection.End; 

那將是解決我問題的最佳方法,還是有一種更簡單的方法來做到這一點?

您可以設置一個按鍵事件,在觸發該事件時,驗證按鍵和所需的長度,並在需要時附加Environment.NewLine。

我認為這是一個棘手的問題,他的代碼幾乎可以解決這個問題:

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;
    }

}

但是我認為應該有更好的方法來做到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM