问题
I have a rich text box that i am using to display an example of the Hello World program and want the keywords such as 'using' 'namespace' 'class' 'static' 'void' 'string' to display blue.
I have got 'using' to display blue but only when the user starts to type or types 'using' I want the richtextbox to be read only not allowing an user input into it
Here is my code:
private void rtb_TextChanged(object sender, EventArgs e)
{
string find = "using";
if (rtb.Text.Contains(find))
{
var matchString = Regex.Escape(find);
foreach (Match match in Regex.Matches(rtb.Text, matchString))
{
rtb.Select(match.Index, find.Length);
rtb.SelectionColor = Color.Blue;
rtb.Select(rtb.TextLength, 0);
rtb.SelectionColor = rtb.ForeColor;
};
}
}
I am having trouble figuring out how to do it for readonly rtb. How could i edit my code to display the blue text on initialize in a readonly rtb
Thanks for your help
回答1:
There's no need to subscribe to the TextChanged
event.
Place your code in a separate method:
private void ApplySyntaxHighlite()
{
string find = "using";
if (richTextBox1.Text.Contains(find))
{
var matchString = Regex.Escape(find);
foreach (Match match in Regex.Matches(richTextBox1.Text, matchString))
{
richTextBox1.Select(match.Index, find.Length);
richTextBox1.SelectionColor = Color.Blue;
richTextBox1.Select(richTextBox1.TextLength, 0);
richTextBox1.SelectionColor = richTextBox1.ForeColor;
};
}
}
And call it after you set the text in the RichTextBox
:
richTextBox1.Text =
"using System;\r\nusing System.IO;\r\n\r\nConsole.WriteLine(\"Hello world.\");";
ApplySyntaxHighlite();
来源:https://stackoverflow.com/questions/29396076/readonly-richtextbox-changing-color-of-keyword-c-sharp