0

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

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();
        }
    }
4

1 回答 1

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();
}
于 2013-09-06T18:39:11.300 回答