"About font formatting"
Set is the color of the first character, when the RichTextBox Rich text records the color of position 0, reset text, the position in RTF from position 0 start, so the color is color.red, the third time should be the same
richTextBox1.Text = "123";
richTextBox1.Select(0, 1);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.Clear();//清除文本,包括样式
//或richTextBox1.Text="";
richTextBox1.Text = "abc";
richTextBox1.Text = "efg";
This resets the text color to be black.
"Keyword Coloring"
public partial class Richtextbox:form
... {
Public RichTextBox ()
... {
InitializeComponent ();
}
private void Tsql_textchanged (object sender, EventArgs e)//text box changes event
... {
int index = This.tSql.SelectionStart; Record the location of the modification
This.tSql.SelectAll ();
This.tSql.SelectionColor = Color.Black;
string[] Keystr = ... {' Select ', ' from ', ' where ', ' and ', ' or ', ' order ', ' by ', ' desc ', ' when ', ' case ', '
Then ', ' End ', ' On ', ' in ', ' is ', ' else ', ' left ', ' join ', ' not ', ' null '};
for (int i = 0; i < Keystr. Length; i++)
This.getbunch (Keystr[i], this.tSql.Text);
This.tSql.Select (index, 0); Returns the modified location
This.tSql.SelectionColor = Color.Black;
Public int Getbunch (string p, string s)//coloring keywords
... {
int cnt = 0; int M = p.length; int N = s.length;
Char[] ss = S.tochararray (), pp = p.tOchararray ();
if (M > N) return 0;
for (int i = 0; i < n-m + 1; i++)
... {
Int J;
for (j = 0; J < M; j +)
... {
if (ss[i + j]!= Pp[j]) break;
}
if (j = = P.length)
... {
This.tSql.Select (i, p.length);
This.tSql.SelectionColor = Color.Blue;
cnt++;
}
}
return cnt;
}
}
"Draw color Proposal"
The best practice is to inherit RichTextBox and overload the paint method of the new class.
And when setting selectionlength, the control's redrawing process is forbidden, so that the text that is highlighted by the syntax has a sudden selection process.
The following 2 methods will help you solve the problem.
[DllImport("user32")]
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, IntPtr lParam);
private const int WM_SETREDRAW = 0xB;
//停止控件的重绘
private void BeginPaint()
{
SendMessage(yourRichTextBox.Handle, WM_SETREDRAW, 0, IntPtr.Zero);
}
//允许控件重绘.
private void EndPaint()
{
SendMessage(yourRichTextBox.Handle, WM_SETREDRAW, 1, IntPtr.Zero);
yourRichTextBox.Refresh();
}