using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Text; using System.Windows.Forms; namespace sharpsyntax { public partial class SyntaxTextBox : RichTextBox { private Language language; private bool refreshing; public Language Language { get { return language; } set { language = value; Refresh(); } } [DllImport("user32.dll")] static extern bool LockWindowUpdate(IntPtr hWndLock); public SyntaxTextBox() { InitializeComponent(); refreshing = false; } private void SyntaxTextBox_TextChanged(object sender, EventArgs e) { if (!refreshing) Refresh(); } private void SetColor(int index, int length, Color color) { int selectionStart = SelectionStart; int selectionLenght = SelectionLength; Select(index, length); SelectionColor = color; SelectionStart = selectionStart; SelectionLength = selectionLenght; } private void Reset() { int selectionStart = SelectionStart; int selectionLenght = SelectionLength; SelectAll(); ResetFont(); Font = DefaultFont; SelectionColor = Color.Black; SelectionCharOffset = 0; SelectionStart = selectionStart; SelectionLength = selectionLenght; } public override void Refresh() { refreshing = true; base.Refresh(); if (language == null) return; try { LockWindowUpdate(Handle); Reset(); foreach (MatchGroup group in language.Groups) { if (group.Enabled) { foreach (Match match in language.Matches(group, Text)) { SetColor(match.Index, match.Length, group.Color); } } } } finally { LockWindowUpdate(IntPtr.Zero); refreshing = false; } } } }