Selectively coloring text in RichTextBox

后端 未结 4 1844
深忆病人
深忆病人 2020-11-28 14:50

How can I paint in red every time I meet the letter \"A\" in RichTextBox?

4条回答
  •  盖世英雄少女心
    2020-11-28 15:12

    Here is a snippet out of my wrapper class to do this job:

        private delegate void AddMessageCallback(string message, Color color);
    
        public void AddMessage(string message)
        {
            Color color = Color.Empty;
    
            string searchedString = message.ToLowerInvariant();
    
            if (searchedString.Contains("failed")
                || searchedString.Contains("error")
                || searchedString.Contains("warning"))
            {
                color = Color.Red;
            }
            else if (searchedString.Contains("success"))
            {
                color = Color.Green;
            }
    
            AddMessage(message, color);
        }
    
        public void AddMessage(string message, Color color)
        {
            if (_richTextBox.InvokeRequired)
            {
                AddMessageCallback cb = new AddMessageCallback(AddMessageInternal);
                _richTextBox.BeginInvoke(cb, message, color);
            }
            else
            {
                AddMessageInternal(message, color);
            }
        }
    
        private void AddMessageInternal(string message, Color color)
        {
            string formattedMessage = String.Format("{0:G}   {1}{2}", DateTime.Now, message, Environment.NewLine);
    
            if (color != Color.Empty)
            {
                _richTextBox.SelectionColor = color;
            }
            _richTextBox.SelectedText = formattedMessage;
    
            _richTextBox.SelectionStart = _richTextBox.Text.Length;
            _richTextBox.ScrollToCaret();
        }
    

    Now you can call it with AddMessage("The command failed") to get it automatically highlight in red. Or you can call it with AddMessage("Just a special message", Color.Purple) to define a special color (Helpful e.g. within catch blocks to define a specific color, regardless of the message content)

提交回复
热议问题