使用C#在TextBox中更改一个单词颜色

时间:2013-09-06 16:21:26

标签: c# colors textbox

我有一个名为txtMessages的文本框,我想更改该TextBox中的文本颜色,但不是整个文本。例如:

  

KrAToS:你好我有问题

我想要的部分KrAToS(this.client.NetworkName)以红色着色但文本的其余部分保持黑色。

这是我的代码:希望任何人都能提前感谢

    private void SendMessage()
    {
        if ( this.client.Connected && this.txtNewMessage.Text.Trim() != "" )
        {
            this.client.SendCommand(new Proshot.CommandClient.Command(Proshot.CommandClient.CommandType.Message , IPAddress.Broadcast , this.txtNewMessage.Text));
            this.txtMessages.Text += this.client.NetworkName;
            this.txtMessages.Text += " : " + this.txtNewMessage.Text.Trim() + Environment.NewLine;
            this.txtNewMessage.Text = "";
            this.txtNewMessage.Focus();
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以尝试将其与匹配关键字匹配,并根据需要对其进行着色:

Dictionary<string,Color> dict = new Dictionary<string,Color>(StringComparer.CurrentCultureIgnoreCase);
dict.Add(client.NetworkName,Color.Red);
//you can add more pairs
//build the pattern whenever you finish adding more entries to your dict    
string pattern = string.Format("(?i)({0})",string.Join("|",dict.Select(el=>el.Key).ToArray()));
[DllImport("user32")]
private static extern int SendMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam);
//TextChanged event handler for your richTextBox1
private void richTextBox1_TextChanged(object sender, EventArgs e) {
        int currentIndex = richTextBox1.SelectionStart;
        int currentSelectionLength = richTextBox1.SelectionLength;
        //BeginUpdate
        SendMessage(richTextBox1.Handle, 0xb, IntPtr.Zero, IntPtr.Zero);
        var matches = Regex.Matches(richTextBox1.Text, pattern);
        richTextBox1.SelectAll();
        richTextBox1.SelectionColor = Color.Black;
        foreach (Match m in matches)
        {
            richTextBox1.SelectionStart = m.Index;
            richTextBox1.SelectionLength = m.Length;
            richTextBox1.SelectionColor = dict[m.Value];
        }
        richTextBox1.SelectionStart = currentIndex;
        richTextBox1.SelectionLength = currentSelectionLength;
        //EndUpdate
        SendMessage(richTextBox1.Handle, 0xb, new IntPtr(1), IntPtr.Zero);            
        richTextBox1.Invalidate();
}