在RichTextBox中更改彩色字符串的一部分

时间:2015-07-17 03:03:03

标签: c# .net

我有一个带有完整字符串的RichTextBox。我需要为与名称相对应的所有单词着色,例如玛塔,奥斯卡和里卡多。我怎样才能做到这一点?

这是我到目前为止的代码。它替换了字符串并将其放入RichTextBox:

private void btnFormat_Click(object sender, EventArgs e)
{
    string query_orig = rtxtQuery.Text;
    string qry_reemp_oscar = query_orig.Replace("oscar", "OSCAR");
    string qry_reemp_marta= qry_reemp_coma.Replace("marta", "MARTA");
    string qry_reemp_final = qry_reemp_select.Replace(
        " ricardo ", System.Environment.NewLine + " RICARDO ");
    rtxtQryLinea.Text = qry_reemp_final;
}

2 个答案:

答案 0 :(得分:0)

你可以试试这个

int pos = rtb.TextLength;
rtb.AppendText(txt);
rtb.Select(pos, txt.Length);
rtb.SelectionColor = col;
rtb.Select();

答案 1 :(得分:0)

试试这个

string query_orig = rtxtQuery.Text;
query_orig = query_orig.Replace("oscar", "OSCAR");
query_orig = query_orig.Replace("marta", "MARTA");
query_orig = query_orig.Replace("ricardo ", "RICARDO ");
 rtxtQryLinea.Text = query_orig;

rtxtQryLinea.Select(query_orig.IndexOf("OSCAR"), "OSCAR".Length);
rtxtQryLinea.SelectionColor = Color.Aqua;

rtxtQryLinea.Select(query_orig.IndexOf("MARTA"), "MARTA".Length);
rtxtQryLinea.SelectionColor = Color.Coral;

rtxtQryLinea.Select(query_orig.IndexOf("RICARDO"), "RICARDO".Length);
rtxtQryLinea.SelectionColor = Color.OrangeRed;