每次遇到RichTextBox中的字母“A”时,如何用红色绘画?
答案 0 :(得分:26)
试试这个:
static void HighlightPhrase(RichTextBox box, string phrase, Color color) {
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ; ) {
int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
if (jx < 0) break;
box.SelectionStart = jx;
box.SelectionLength = phrase.Length;
box.SelectionColor = color;
ix = jx + 1;
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
...
private void button1_Click(object sender, EventArgs e) {
richTextBox1.Text = "Aardvarks are strange animals";
HighlightPhrase(richTextBox1, "a", Color.Red);
}
答案 1 :(得分:2)
以下是我的包装类中的一个片段来完成这项工作:
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();
}
现在您可以使用AddMessage("The command failed")
调用它以使其自动以红色突出显示。或者您可以使用AddMessage("Just a special message", Color.Purple)
调用它来定义一种特殊颜色(例如,在catch块中有用以定义特定颜色,无论消息内容如何)
答案 2 :(得分:1)
如果你正在寻找的话,这将无法正常工作,但我用它来突出显示子串:
Function Highlight(ByVal Search_Str As Object, ByVal InputTxt As String, ByVal StartTag As String, ByVal EndTag As String) As String
Highlight = Regex.Replace(InputTxt, "(" & Regex.Escape(Search_Str) & ")", StartTag & "$1" & EndTag, RegexOptions.IgnoreCase)
End Function
并以这种方式称呼它:
Highlight("A", "Color All my A's red", [span class=highlight]', '[/span]')
“强调”类具有您想要的任何颜色编码/格式:
.highlight {text-decoration: none;color:black;background:red;}顺便说一句:你需要将那些方括号改为有角度的方括号...当我输入它们时它们不会通过......
答案 3 :(得分:1)
这是EJ Brennan回答的C#代码:
public string Highlight(object Search_Str, string InputTxt, string StartTag, string EndTag)
{
return Regex.Replace(InputTxt, "(" + Regex.Escape(Search_Str) + ")", StartTag + "$1" + EndTag, RegexOptions.IgnoreCase);
}