如何禁用编辑 RichTextBox 的第一行?

How to disable edit first line of RichTextBox?

我通过

设置了 richtextbox 的第一行
RichTextBox.text = "Comment:";

我希望此行只读,从第二行开始输入,并从第二行开始获取文本。

有什么建议吗?谢谢!


谢谢,我添加了一个 MouseClick 事件来禁止第一行可编辑:

 private void CommentTxtBox_MouseClick(object sender, MouseEventArgs e)
    {
        int index = _commentTxtBox.SelectionStart;
        int line = _commentTxtBox.GetLineFromCharIndex(index);
        if (line == 0)
        {
            _commentTxtBox.ReadOnly = true;
        }
        else
            _commentTxtBox.ReadOnly = false;

    }

您可以使用SelectionProtected

Gets or sets a value indicating whether the current text selection is protected.

例如,您在控件中有 "Comment:",用户可以在其后追加文本但不能删除您的文本。

因此,我将前 7 个字符设置为 ReadOnly,附加一个换行符,您的控件的其余部分将变为可修改:

RichTextBox.Select(0, "Comment:".Length);
RichTextBox.SelectionProtected = true;
RichTextBox.AppendText(Environment.NewLine);

你可以试试这个:

private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
    int line = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart);
    richTextBox1.ReadOnly = line == 0;
}

没有经过严格测试;它只允许您在 selection/cursor 不在第一行时进行编辑..