程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> C# richTextbox的字體格式和顏色

C# richTextbox的字體格式和顏色

編輯:關於C#

【關於字體格式】

設置的是第一個字符的顏色,這時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();
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved