我想在RichTextbox
中,在特定位置和特定颜色处插入一个字符串。所以我尝试为AppendText()
类的方法RichTextbox
添加扩展名。
public static void AppendText(this RichTextBox Box, string Text, Color col, int SelectionStart)
{
Box.SelectionStart = SelectionStart;
Box.SelectionLength = 0;
Box.SelectionColor = col;
Box.SelectionBackColor = col;
Box.Text = Box.Text.Insert(SelectionStart, Text);
Box.SelectionColor = Box.ForeColor;
}
我试图在名为RichTextBoxExtension
的类中使用它。结果不符合我的期望。插入字符串但不选择所选颜色。
有没有更好的方法来执行此功能?
答案 0 :(得分:1)
您必须使用RichTextBox控件的SelectedText
属性。还要确保在更改任何内容之前跟踪当前选择的值。
你的代码看起来应该是这样的(我放弃了Hans所暗示的):
public static void AppendText(this RichTextBox Box,
string Text,
Color col,
int SelectionStart)
{
// keep all values that will change
var oldStart = Box.SelectionStart;
var oldLen = Box.SelectionLength;
//
Box.SelectionStart = SelectionStart;
Box.SelectionLength = 0;
Box.SelectionColor = col;
// Or do you want to "hide" the text? White on White?
// Box.SelectionBackColor = col;
// set the selection to the text to be inserted
Box.SelectedText = Text;
// restore the values
// make sure to correct the start if the text
// is inserted before the oldStart
Box.SelectionStart = oldStart < SelectionStart ? oldStart : oldStart + Text.Length;
// overlap?
var oldEnd = oldStart + oldLen;
var selEnd = SelectionStart + Text.Length;
Box.SelectionLength = (oldStart < SelectionStart && oldEnd > selEnd) ? oldLen + Text.Length : oldLen;
}