对于Windows窗体。
我正在尝试将文本插入RichTextBox的.rtf字段中。
我尝试了两种方法。当我使用.Rtf.insert时,根本没有任何反应。
当我根据所选文本位置自己编辑.rtf字符串时,要么添加了无意义的东西,要么出现错误,指出文件格式无效。我最好的猜测是因为.rtf字符串处于.rtf格式中,而我使用的选择索引基于纯文本字符串,所以我在.rtf字符串中插入了错误的位置,并且搞乱了RTF代码。
但是,知道问题所在(如果我是正确的)并没有帮助我解决它。
有没有办法使.rtf.insert正常工作,或者有没有办法将所选文本索引转换为实际的.rtf文本位置,以便像下面的代码一样工作?我假设RichTextBox本身必须知道如何将一个索引转换为另一个,因为它可以在用户键入时插入字符。
这是我的代码片段。代码的目的是在文本中插入一个标记,稍后将对其进行解析并用学生的名字替换。还会有其他类似的代码。 "codeLeader"和"codeEnder"只是我用来包围代码的字符串。在这种情况下,我使用"[*"和*]"来表示我将需要解析的代码,但我将它们放入单独的字符串中,以便在需要时可以轻松更改。我已经编写了解析代码,对于富文本,它可以正常工作。问题在于将文本插入到richTextBox本身中。换句话说,如果我手动输入代码,它会正常工作。但是这对用户来说很麻烦,因为一些代码将使用索引号。
private void studentFirstNameCode_Click(object sender, EventArgs e)
{
string ins = f1ref.codeLeader;
ins += "SNFirst" + f1ref.codeEnder;
int start = editorField.richTextBox1.SelectionStart;
if (start == -1) { start = 0; }
int end = start + editorField.richTextBox1.SelectionLength;
if (end == -1) { end = 0; }
string pre = editorField.richTextBox1.Rtf.Substring(0, start);
string post = editorField.richTextBox1.Rtf.Substring(end);
string newstring = pre + ins + post;
editorField.richTextBox1.Rtf = newstring;
// this also doesn't work. gives no result at all.
// editorField.richTextBox1.Rtf.Insert(start, newstring);
}