using System; using System.Windows.Forms; using System.Drawing; using System.Text.RegularExpressions; public class Test : Form { RichTextBox m_rtb = null; public static void Main() { Application.Run(new Test()); } public Test() { Text = "Test"; ClientSize = new Size(400, 400); m_rtb = new RichTextBox(); m_rtb.Multiline = true; m_rtb.WordWrap = false; m_rtb.AcceptsTab = true; m_rtb.ScrollBars = RichTextBoxScrollBars.ForcedBoth; m_rtb.Dock = DockStyle.Fill; m_rtb.SelectionFont = new Font("Courier New", 10, FontStyle.Regular); m_rtb.SelectionColor = Color.Black; Controls.Add(m_rtb); Parse(); } void Parse() { String inputLanguage = "// Comment.\n" + "using System;\n" + "\n" + "public class Stuff : Form { \n" + " public static void Main(String args) {\n" + " }\n" + "}\n"; // Foreach line in input, // identify key words and format them when adding to the rich text box. Regex r = new Regex("\\n"); String[] lines = r.Split(inputLanguage); foreach (string l in lines) { ParseLine(l); } } void ParseLine(string line) { Regex r = new Regex("([ \\t{}();])"); String[] tokens = r.Split(line); foreach (string token in tokens) { // Set the token's default color and font. m_rtb.SelectionColor = Color.Black; m_rtb.SelectionFont = new Font("Courier New", 10, FontStyle.Regular); // Check for a comment. if (token == "//" || token.StartsWith("//")) { // Find the start of the comment and then extract the whole comment. int index = line.IndexOf("//"); string comment = line.Substring(index, line.Length - index); m_rtb.SelectionColor = Color.LightGreen; m_rtb.SelectionFont = new Font("Courier New", 10, FontStyle.Regular); m_rtb.SelectedText = comment; break; } // Check whether the token is a keyword. String[] keywords = { "public", "void", "using", "static", "class" }; for (int i = 0; i < keywords.Length; i++) { if (keywords[i] == token) { // Apply alternative color and font to highlight keyword. m_rtb.SelectionColor = Color.Blue; m_rtb.SelectionFont = new Font("Courier New", 10, FontStyle.Bold); break; } } m_rtb.SelectedText = token; } m_rtb.SelectedText = "\n"; } }