C# richTextbox的 字体格式颜色

【关于字体格式】

设置的是第一个字符的颜色,这时richtextBox的rtf中记录下位置0的颜色,重置text时,在rtf中的位置从位置0开始,因此颜色还是Color.Red,第三次也应该同样如此
richTextBox1.Text = "123";
richTextBox1.Select(0, 1);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.Clear();//清除文本,包括样式
//或richTextBox1.Text="";
richTextBox1.Text = "abc";
richTextBox1.Text = "efg";
这样重置后的文本颜色就会是黑色.

【关键字着色】

public partial class RichTextBox : Form
 {
        public RichTextBox()
        {
             InitializeComponent();
         }

        private void tSql_TextChanged(object sender, EventArgs e) //文本框改变事件
        {
            int index = this.tSql.SelectionStart;    //记录修改的位置
            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);     //返回修改的位置
            this.tSql.SelectionColor = Color.Black;

         }
        public int getbunch(string p, string s) //给关键字上色
        {
            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;

         }

     }


【绘制颜色提议】

最好的做法是继承RichTextBox,重载新类的Paint方法。

并且在设置SelectionLength的时候,禁止控件的重绘过程,这样才不会出现被语法高亮的文本有一个突然选中的过程。

以下2个方法将会对你解决这一问题有很大的帮助.
[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();
}

 

你可能感兴趣的:(C#)