(轉)winform之RichTextBox

RichTextBox是一種可用於顯示、輸入和操做格式文本,除了能夠實現TextBox的全部功能,還能提供富文本的顯示功能。 控件除具備TextBox 控件的全部功能外,還能設定文字顏色、字體和段落格式,支持字符串查找功能,支持rtf格式等功能。html

下面就其的經常使用到的功能進行介紹。數組

1、顯示滾動條

RichTextBox可設置Multiline屬性來控制是否顯示滾動套,true爲是,false爲否。,默認爲true。(此項屬性在TextBox亦可實現)瀏覽器

滾動條分爲兩種:水平(Horizontal)滾動條和垂直(Vertical)滾動條,經過RichTextBox的ScrollBars屬性設置如何顯示滾動條。(此項屬性在TextBox亦可實現)ide

ScrollBars屬性值:post

一、Both:只有當文本超過RichTextBox的寬度或長度時,才顯示水平滾動條或垂直滾動條,或兩個滾動條都顯示。字體

二、None:從不顯示任何類型的滾動條。網站

三、Horizontal:只有當文本超過RichTextBox的寬度時,才顯示水平滾動條。必須將WordWrap屬性設置爲false,纔會出現這種狀況。(下面將會給出解釋)this

四、Vertical:只有檔文本超過RichTextBox的高度時,才顯示垂直滾動條。spa

五、ForcedHorizontal:當WordWrap屬性設置爲false時,顯示水平滾動條。在文本未超過RichTextBox的寬度時,該滾動條顯示爲淺灰色。3d

六、ForcedVertical:始終顯示垂直滾動條。在文本未超過RichTextBox的長度時,該滾動條顯示爲淺灰色。

七、ForcedBoth:始終顯示垂直滾動條。當WordWrap屬性設置爲false時,顯示水平滾動條。在文本未超過RichTextBox的寬度或長度時,兩個滾動條均顯示爲灰色。

 

 注:RichTextBox的WordWrap屬性:用於指示多行文本框控件在必要時是否換行到下一行的開始。當屬性爲true時,不論ScrollBars屬性值是什麼,都不會顯示水平滾動條。

下面經過幾個截圖加以描述其區別。(此項屬性TextBox亦可實現)

(1)、當WordWrap爲true,ScrollBars爲Both時:

  

因而可知,WordWrap爲true時,一旦文本超過RichTextBox的寬度時,就會自動換行到下一行,天然不須要用到水平滾動條,也就不顯示出來了。

(2)、當WordWrap爲false,ScrollBars爲Both時:

  

由此可知,WordWrap爲false時,即便文本超過RichTextBox的寬度,也不會自動換行到下一行,只有用戶輸入回車時纔會換行,而且當文本超過RichTextBox的寬度後,纔會顯示水平滾動條。

代碼實現過程:

private  void  Form1_Load( object  sender, EventArgs e)  //窗體的Load事件
{
  richTextBox1.Multiline =   true  ;      //將Multiline屬性設置爲true,實現顯示多行
     richTextBox1.ScrollBars = RichTextBoxScrollBars.Vertical;  //設置ScrollBars屬性實現只顯示垂直滾動
}

2、設置字體屬性

 可經過RichTextBox的Font屬性和ForeColor屬性設置(Visual Studio2013社區版找不到SelectionFont和SelectionColor屬性),也可經過代碼實現,如文本字體設置爲楷體,字體大小爲12,字樣是粗體,文本顏色爲紅色:

private  void  Form1_Load( object  sender, EventArgs e)  //窗體的Load事件
{
  richTextBox1.Multiline =  true  ;   //將Multiline屬性設爲true,實現顯示多行
  richTextBox1.ScrollBars = RichTextBoxScrollBars.Vertical;   //設置ScrollBars屬性實現只顯示垂直滾動條
  richTextBox1.SelectionFont =  new  Font ( "楷體" , 12, FontStyle.Bold);   //設置SelectionFont屬性實現控件中的文本爲楷體,大小爲12,字樣是粗體
  richTextBox1.SelectionColor = System.Drawing.Color.Red;     //設置SelectionColor屬性實現控件中的文本顏色爲紅色
}

將RichTextBox控件顯示爲超連接樣式

將以「http://」開頭的Web連接地址做爲超連接文本時,運行時RichTextBox超連接文本會自動變成藍色字體且有下劃線。

此時點擊超連接文本不會有任何響應,須要在RichTextBox的LinkClicked事件中編寫代碼實現。

private  void  Form1_Load( object  sender, EventArgs e)            //窗體的Load事件
{
  richTextBox1.Multiline =  true  ;    //將Multiline屬性設爲true,實現顯示多行
  richTextBox1.ScrollBars = RichTextBoxScrollBars.Vertical;    //設置ScrollBars屬性實現只顯示垂直滾動條
  richTextBox1.Text =  "http://www.baidu.com百度一下你就知道" ;   //設置Text屬性
}
 
private  void  richTextBox1_LinkClicked( object  sender, EventArgs e)
{
  System.Diagnostics.Process.Start(e.LinkText);                    //在控件LinkClicked事件中編寫以下代碼實現內容中的網址單擊後能夠訪問網址
}

3、設置段落格式

可經過設置SelectionBullet屬性將選定的段落設置爲項目符號列表的格 式,也可使用SelectionIndent屬性和SelectionHangingIndent屬性設置段落相對於控件的左右邊緣進行縮進。下面用代 碼將控件的SelectionBullet屬性設置爲true,使控件中的內容以項目符號列表的格式排列。

private  void  Form1_Load( object  sender, EventArgs e)
{
  richTextBox1.Multiline =  true  ;   
     richTextBox1.ScrollBars = RichTextBoxScrollBars.Vertical ;
  richTextBox1.SelectionBullet =  true  ;
}

如下爲屬性SelectionBullet設爲false和true時的差別(前者爲false後者爲true):

  

經過SelectionIndent屬性設置一個整數,該整數表示控件的左邊緣和文本的左邊緣之間的距離(以像素爲單位)。經過SelectionRightIndent屬性設置一個整數,該整數表示控件的右邊緣與文本的右邊緣之間的距離(以像素爲單位)。

如下經過代碼實現SelectionIndent屬性設置。

private  void  Form1_Load( object  sender, EventArgs e)
{
  richTextBox1.Multiline =  true  ;
  richTextBox1.ScrollBars = RichTextBoxScrollBars.Vertical ;
  richTextBox1.SelectionIndent = 50 ;
}

差別以下組圖:

  

SelectionRightIndent屬性與SelectionIndent屬性相似,可類比,固然也能夠同時使用。

4、經常使用功能

1.RichTextBox控件的經常使用屬性

1) SelectedText屬性、SelectionLength屬性、SelectionStart屬性——與TextBox控件的屬性功能相同。 
2) SelectionFont:獲取或設置選中的文本或插入點的字體,例如: 
1
richTextBox1.SelectionFont=fontDialog1.Font;  //設置爲字體對話框中選中的字體
3) SelectionColor:獲取或設置選中的文本或插入點的文本顏色。
4) SelectionAlignment:獲取或設置應用到當前選定內容或插入點的對齊方式。
5) Lines屬性——字符串數組。記錄輸入到RichText控件中的全部文本,每按兩次回車鍵之間的字符串是該數組的一個元素。 
6) Modifyed屬性——記錄用戶是否已修改控件中的文本內容。若已修改,該屬性值自動設置爲true。 
7) HideSelection屬性——設置當焦點離開該控件時,選定的文本是否保持突出顯示。值爲false時突出顯示。 

2.RichTextBox控件的經常使用事件

1)SelectionChange事件——控件中選中的文本發生改變時,觸發該事件。  
2)TextChanged事件——控件中的文本內容發生改變時,觸發該事件。

3.RichTextBox控件的經常使用方法

1)Clear( )方法——清除RichText控件中用戶輸入的全部內容。  
2)Copy( )、Cut( )、Paste( )方法——實現RichText控件的剪貼板功能; 
3)SelectAll( )方法——選中控件中的全部文本。  4)Find( )方法——實現查找功能。 
5)SaveFile( )方法、LoadFile( )方法——保存文本和打開文件。 
6)Undo( )方法、Redo( )方法——撤銷上一次編輯操做、重作上次撤銷的編輯操做。   
說明:常與CanUndo屬性和CanRedo屬性配合使用。 
7)LoadFile()——加載文本文件(*.txt)或RTF文件(*.rtf)。  
8)SaveFile()——保存文本文件(*.txt)或RTF文件(*.rtf)。

 4. 將文件加載到RichTextBox 對象中  

使用LoadFile( )方法.
(1)通常格式 
RichTextBox對象名.LoadFile(文件名,文件類型);   
(2)說明 
RichTextBox 控件能夠顯示純文本、Unicode 純文本或 RTF 格式文件。若要顯示這些文件,可調用 LoadFile 方法。例如,使用打開文件對話框選擇一個文本文件並加載到richTextBox1控件中,代碼以下:  

openFileDialog1.Filter= "文本文件(*.txt)|*.txt|全部文件(*.*)|*.*" ;
if (openFileDialog1.ShowDialog()==DialogResult.OK)
{    
      string  fName=openFileDialog1.FileName;
      richTextBox1.LoadFile(fName,RichTextBoxStreamType.PlainText  );
}

RichTextBoxStreamType.PlainText爲加載的文件類型,其餘可選的枚舉值以下:

5. 保存RichTextBox 對象中的文件

用SaveFile( )方法
(1)通常格式 
RichTextBox對象名.SaveFile(文件名,文件類型);    
(2)使用說明 
同LoadSave( )方法。
//保存RTF格式文件
saveFileDialog1.Filter= "RTF文件(*.rtf)|*.rtf" ; saveFileDialog1.DefaultExt= "rtf" ;<br> //默認的文件擴展名
if (saveFileDialog1.ShowDialog()==DialogResult.OK)
richTextBox1.SaveFile(saveFileDialog1.FileName,RichTextBoxStreamType.RichText );

6. 插入圖片文件

可藉助剪貼板實現.

Clipboard.Clear();    //清空剪貼板
Bitmap bmp =  new  Bitmap( @"d:\圖片1.jpg" );   //建立Bitmap類對象
Clipboard.SetImage(bmp);   //將Bitmap類對象寫入剪貼板
richTextBox1.Paste();    //將剪貼板中的對象粘貼到RichTextBox1

7. 其它補充內容

TextBox控件用到的全部屬性、事件和方法,RichTextBox控件幾乎都能支持,例如 MaxLength、MultiLine、ScrollBars、SelLength、SelStart 和 SelText。
注意:
TextBoxBase.Undo 方法不可用於 KeyPress 或 TextChanged 事件。
RichTextBox 控件沒有TextBox控件同樣具備64K字符容量的限制。 
RichTextBox 控件提供許多可對控件內任何文本部分應用格式設置的屬性。若要更改文本的格式設置,必須首先選定此文本。只能爲選定的文本分配字符和段落格式設置。對選定 的文本內容進行設置後,在選定內容後輸入的全部文本也用相同的設置進行格式設置,直到更改設置或選定控件文檔的不一樣部分爲止。SelectionFont 屬性使您得以將文本以粗體或斜體顯示。還可使用此屬性更改文本的大小和字樣。SelectionColor 屬性使您得以更改文本的顏色。若要建立項目符號列表,可使用 SelectionBullet 屬性。還能夠經過設置 SelectionIndent、SelectionRightIndent 和 SelectionHangingIndent 屬性調整段落格式設置。

 

RichTextBox 控件提供具備打開和保存文件的功能的方法。
LoadFile 方法使您得以將現有的 RTF 或 ASCII 文本文件加載到控件中。還能夠從已打開的數據流加載數據。SaveFile 使您得以將文件保存到 RTF 或 ASCII 文本中。與 LoadFile 方法類似,還可使用 SaveFile 方法保存到開放式數據流。

 
Find 方法被重載,能夠同時查找控件文本內的文本字符串以及特定字符。 
也能夠將 RichTextBox 控件初始化爲內存中存儲的數據。例如,能夠將 Rtf 屬性初始化爲包含要顯示文本的字符串,包括肯定如何設置該文本格式的 RTF 代碼。 
可使用 DetectUrls 屬性適當地顯示控件文本中的連接(如到網站的連接)。而後能夠處理 LinkClicked 事件以執行與該連接關聯的任務。 
SelectionProtected 屬性使您得以保護控件內的文本不被用戶操做。當控件中有受保護的文本時,能夠處理 Protected 事件以肯定用戶什麼時候曾試圖修改受保護的文本,並提醒用戶該文本是受保護的,或向用戶提供標準方式供其操做受保護的文本。
 
例1
將 RTF 文件加載到控件中並搜索單詞「Text」的第一個實例。而後代碼更改選定文本的字體樣式、字體大小和字體顏色並將更改保存到原始文件。
//部分文字屬性的更改
public void CreateMyRichTextBox() { RichTextBox richTextBox1 = new RichTextBox(); richTextBox1.Dock = DockStyle.Fill; richTextBox1.LoadFile("C:\\MyDocument.rtf"); richTextBox1.Find("Text", RichTextBoxFinds.MatchCase); richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Bold); richTextBox1.SelectionColor = Color.Red; richTextBox1.SaveFile("C:\\MyDocument.rtf", RichTextBoxStreamType.RichText); this.Controls.Add(richTextBox1); }
複製代碼
public void CreateMyRichTextBox()
{
    RichTextBox richTextBox1 = new RichTextBox();
    richTextBox1.Dock = DockStyle.Fill;

    richTextBox1.LoadFile("C:\\MyDocument.rtf");
    richTextBox1.Find("Text", RichTextBoxFinds.MatchCase);

    richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);
    richTextBox1.SelectionColor = Color.Red;

    richTextBox1.SaveFile("C:\\MyDocument.rtf", RichTextBoxStreamType.RichText);

    this.Controls.Add(richTextBox1);
}
複製代碼

 

例2

更加複雜的多媒體類型的文字段落的錄入

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Win_Test
{
    public partial class RichTextBox_Test : Form
    {
        public RichTextBox_Test()
        {
            InitializeComponent();
        }

        Font oldFont;
        Font newFont;

        //richTextBox1 所選文字加粗
        private void button1_Click(object sender, EventArgs e)
        {
       oldFont = this.richTextBox1.SelectionFont;
            if (oldFont.Bold)
            { 
          newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Bold);
       } else
       { newFont = new Font(oldFont, oldFont.Style | FontStyle.Bold);
       }
        this.richTextBox1.SelectionFont = newFont; this.richTextBox1.Focus(); } //richTextBox1 所選文字加下劃線 private void button2_Click(object sender, EventArgs e) { oldFont = this.richTextBox1.SelectionFont; if (oldFont.Underline) {
         newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Underline);
       } else
       {  newFont = new Font(oldFont, oldFont.Style | FontStyle.Underline);
       }
  this.richTextBox1.SelectionFont = newFont; this.richTextBox1.Focus(); } //richTextBox1 所選文字爲斜體 private void button3_Click(object sender, EventArgs e) { oldFont = this.richTextBox1.SelectionFont; if (oldFont.Italic) {
         newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Italic);
       } else        { newFont = new Font(oldFont, oldFont.Style | FontStyle.Italic);
       }
this.richTextBox1.SelectionFont = newFont; this.richTextBox1.Focus(); } //richTextBox1 所選文字居中 private void button4_Click(object sender, EventArgs e) { if (this.richTextBox1.SelectionAlignment == HorizontalAlignment.Center) {
         this.richTextBox1.SelectionAlignment = HorizontalAlignment.Left;
       } else
       { this.richTextBox1.SelectionAlignment = HorizontalAlignment.Center;
       }
this.richTextBox1.Focus(); } // 在文本框輸入字體大小 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { //remove all characters that are not numbers,backspace and enter if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13) {
         e.Handled = true;
       } else if (e.KeyChar == 13) { TextBox txt = (TextBox)sender; if (txt.Text.Length > 0) ApplyTextSize(txt.Text); e.Handled = true; this.richTextBox1.Focus(); } } //根據textBox1的值設置richTextBox1的字體 private void ApplyTextSize(string textSize) { float newSize = Convert.ToSingle(textSize); FontFamily currentFontFamily; Font newFont; currentFontFamily = this.richTextBox1.SelectionFont.FontFamily; newFont = new Font(currentFontFamily, newSize); this.richTextBox1.SelectionFont = newFont; } //在textBox1控件驗證時觸發,設置richTextBox1的字體 private void textBox1_Validating(object sender, CancelEventArgs e) { TextBox txt = (TextBox)sender; ApplyTextSize(txt.Text); this.richTextBox1.Focus(); } //讓瀏覽器打開超連接地址 private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e) { System.Diagnostics.Process.Start(e.LinkText); } //richTextBox1 加載 Test.rtf 文件 private void button5_Click(object sender, EventArgs e) { try { richTextBox1.LoadFile("Test.rtf"); } catch (System.IO.FileNotFoundException) { MessageBox.Show("No file to be load yet"); } } //richTextBox1 保存到 Test.rtf 文件 private void button6_Click(object sender, EventArgs e) { try { richTextBox1.SaveFile("Test.rtf"); } catch (System.Exception err) { MessageBox.Show(err.Message); } } } }
複製代碼
Demo

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Win_Test
{
    public partial class RichTextBox_Test : Form
    {
        public RichTextBox_Test()
        {
            InitializeComponent();
        }

        Font oldFont;
        Font newFont;

        //richTextBox1 所選文字加粗
        private void button1_Click(object sender, EventArgs e)
        {

            oldFont = this.richTextBox1.SelectionFont;
            if (oldFont.Bold)
            { newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Bold); }
            else
                newFont = new Font(oldFont, oldFont.Style | FontStyle.Bold);

            this.richTextBox1.SelectionFont = newFont;
            this.richTextBox1.Focus();

        }

        //richTextBox1 所選文字加下劃線
        private void button2_Click(object sender, EventArgs e)
        {
            oldFont = this.richTextBox1.SelectionFont;
            if (oldFont.Underline)
            { newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Underline); }
            else
                newFont = new Font(oldFont, oldFont.Style | FontStyle.Underline);
            this.richTextBox1.SelectionFont = newFont;
            this.richTextBox1.Focus();


        }

        //richTextBox1 所選文字爲斜體
        private void button3_Click(object sender, EventArgs e)
        {
            oldFont = this.richTextBox1.SelectionFont;
            if (oldFont.Italic)
            { newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Italic); }
            else

                newFont = new Font(oldFont, oldFont.Style | FontStyle.Italic);
            this.richTextBox1.SelectionFont = newFont;
            this.richTextBox1.Focus();
        }

        //richTextBox1 所選文字居中
        private void button4_Click(object sender, EventArgs e)
        {
            if (this.richTextBox1.SelectionAlignment == HorizontalAlignment.Center)
                this.richTextBox1.SelectionAlignment = HorizontalAlignment.Left;
            else
                this.richTextBox1.SelectionAlignment = HorizontalAlignment.Center;
            this.richTextBox1.Focus();
        }


        // 在文本框輸入字體大小
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            //remove all characters that are not numbers,backspace and enter
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13)
            { e.Handled = true; }
            else if (e.KeyChar == 13)
            {
                TextBox txt = (TextBox)sender;
                if (txt.Text.Length > 0)
                    ApplyTextSize(txt.Text);
                e.Handled = true;
                this.richTextBox1.Focus();
            }
        }

        //根據textBox1的值設置richTextBox1的字體
        private void ApplyTextSize(string textSize)
        {
            float newSize = Convert.ToSingle(textSize);
            FontFamily currentFontFamily;
            Font newFont;
            currentFontFamily = this.richTextBox1.SelectionFont.FontFamily;
            newFont = new Font(currentFontFamily, newSize);
            this.richTextBox1.SelectionFont = newFont;
        }

        //在textBox1控件驗證時觸發,設置richTextBox1的字體
        private void textBox1_Validating(object sender, CancelEventArgs e)
        {
            TextBox txt = (TextBox)sender;
            ApplyTextSize(txt.Text);
            this.richTextBox1.Focus();
        }

        //讓瀏覽器打開超連接地址
        private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(e.LinkText);
        }

        //richTextBox1 加載 Test.rtf 文件
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                richTextBox1.LoadFile("Test.rtf");
            }
            catch (System.IO.FileNotFoundException)
            {
                MessageBox.Show("No file to be load yet");
            }
        }

        //richTextBox1 保存到 Test.rtf 文件
        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                richTextBox1.SaveFile("Test.rtf");
            }
            catch (System.Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

    }
}
複製代碼
 文章轉載自https://www.cnblogs.com/arxive/p/5725570.html
相關文章
相關標籤/搜索