2016-07-06 78 views
2

我想在我的RichTextbox中,特定位置和特定颜色中插入一个字符串。所以我试着为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的类中使用它。结果不符合我的预期。该字符串已插入,但未与所选颜色一起使用。 有没有更好的方法来做这个功能?

编辑:我认为这可能是有趣的告诉你为什么我需要这个功能。实际上,当用户写一个右括号时,我想高亮(或彩色)相关的左括号。 因此,例如,如果用户编写(Mytext),当用户点击“)”时,第一个括号将变为彩色,并将选择保留在该括号上。

+2

设置Text属性将导致丢失所有格式。您必须改为指定SelectionText属性。恢复SelectionStart和SelectionLength属性是必需的。你会发现你自己的颜色选择错误。 –

+0

我知道这是一个WinForms问题,但如果有人从WPF-o-sphere失败,可以使用'Document'属性很容易地访问RichTextBox的底层'FlowDocument'。 - 这有一个更强大的编辑API(并且应该优先于WinForms编辑器,其他高级功能如拼写检查等)。 - 如果您被困在WinForms中,可能值得考虑在'ElementHost'控件中托管WPF Rich Text编辑器。 – BrainSlugs83

回答

1

您必须使用RichTextBox控件的SelectedText属性。在更改任何内容之前,请确保跟踪当前选择的值。

您的代码应该是这样的(我放弃什么汉斯在被暗示):

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

非常感谢您的帮助!我会尝试这个解决方案,并会尽快给你一个反馈。只是为了确定我明白:属性selectedText实际上是我想要修改颜色的文本?另外,我光标会停留在这个文本上选择否?事实上,举个例子,如果我写“(myvalue)”时,我会写“)”,左括号“(”会突出显示,但是如果我继续写东西,是否可以“删除”行动“?如果我的问题不清楚,请告诉我。对于错误抱歉,我知道我的英语不完美^^' – Seraphon91

相关问题