Reputation: 1018
I have Rich TextBox to Edit XML Text
What i want how to color the XML Tags Names inside the RichTextBox
I want the tags names in RED or Green color.
Any Way to do that?
Upvotes: 2
Views: 3063
Reputation: 42229
I think for small syntax highlighting projects, roll your own! There are some examples of highlighting in a syntax editor already posted.
https://stackoverflow.com/a/13007641/1033686
https://stackoverflow.com/a/13007710/1033686
For larger projects that demand better highlighting, use Scintilla.NET (but be warned, it it a bit heavy and can be tricky to get working!)
http://scintillanet.codeplex.com/
For enterprise projects use a commercial product like actipro syntax editor.
Upvotes: 0
Reputation: 23833
Work out what your desired regex is using this page. Once you have this you could use something like the following method to update the RichTextBox
public static void HighlightSyntax(RichTextBox richTextBox, Regex yourRegex, Color someColor)
{
richTextBox.BeginUpdate();
int selPos = richTextBox.SelectionStart;
richTextBox.SelectAll();
richTextBox.SelectionColor = normTextColor;
richTextBox.Select(selPos, 0);
// For each match from the regex, highlight the word.
foreach (Match keyWordMatch in yourRegex.Matches(richTextBox.Text))
{
richTextBox.Select(keyWordMatch.Index, keyWordMatch.Length);
richTextBox.SelectionColor = someColor;
richTextBox.Select(selPos, 0);
richTextBox.SelectionColor = normTextColor;
}
richTextBox.EndUpdate();
}
You could also adopt a timer to update this automatically after a set time.
I hope this helps.
Note. For large text files, and approach like this will be slow! In this case I would adopt Sinctilla.NET as a full syntax highlighter as stated in one of the answers below...
Upvotes: 2
Reputation: 31283
Check out scintilla, a nice source code editing component for Windows which supports Syntax Highlighting too. And there's a .NET wrapper for it called ScintillaNET.
Upvotes: 0
Reputation: 44605
there are articles which explain or suggest possible approaches to syntax colouring, for example: How To Implement Syntax Highlighting In A WinForms Application
I think the best and easiest way is to use Scintilla.NET to handle that so you can focus on what really matters to you instead of reinventing the wheel again :)
Upvotes: 1
Reputation: 13436
Using a simple regex find the location (start and end) of each tag and colorize it like below:
richtextbox1.Select(start, end-start);
richtextbox1.SelectionColor = Color.Green;
richtextbox1.Select(start, 0);
Upvotes: 0