C# RichTextBox 制作文本編輯器


本文利用一個簡單的小例子【文本編輯器】,講解RichTextBox的用法,僅供學習分享使用,如有不足之處,還請指正。

Windows窗體中的RichTextBox控件用於顯示,輸入和操作格式化的文本,RichTextBox除了擁有TextBox控件的所有功能外,還可以顯示字體,顏色,鏈接,從文件中讀取和加載圖像,以及查找指定的字符。RichTextBox控件通常用於提供類似字體處理程序(如Microsoft Word)的文本操作和顯示功能。RichTextBox控件可以顯示滾動條,且默認根據需要進行顯示。

涉及知識點:

  • SelectionFont 獲取或設置當前選定文本或插入點的字體。
  • FontStyle 指定應用到文本的字形信息。
  • SelectionAlignment  獲取或設置應用到當前選定內容或插入點的對齊方式。
  • SelectionIndent 獲取或設置所選內容開始行的縮進距離(以像素為單位)。
  • SelectionCharOffset 獲取或設置控件中的文本是顯示在基線上、作為上標還是作為基線下方的下標。
  • SelectionColor 獲取或設置當前選定文本或插入點的文本顏色。
  • SelectionBackColor   獲取或設置在 System.Windows.Forms.RichTextBox 控件中選中文本時文本的顏色。
  • SelectionBullet 獲取或設置一個值,通過該值指示項目符號樣式是否應用到當前選定內容或插入點。
  • Clipboard Paste 粘貼指定剪貼板格式的剪貼板內容【插入圖片時使用】。
  • Find 在對搜索應用特定選項的情況下,在 System.Windows.Forms.RichTextBox 控件的文本中搜索位於控件內特定位置的字符串。

效果圖

如下【以下設置文本對應的格式】:

核心代碼

如下

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Drawing;
  4 using System.Drawing.Printing;
  5 using System.Linq;
  6 using System.Text;
  7 using System.Threading.Tasks;
  8 using System.Windows.Forms;
  9 
 10 namespace DemoRichText.Model
 11 {
 12     public class DefaultRickFormat : BaseRichFormat
 13     {
 14         public override void SetFormat(RichTextBox rtbInfo)
 15         {
 16 
 17         }
 18     }
 19 
 20     /// <summary>
 21     /// 加粗格式
 22     /// </summary>
 23     public class BoldRichFormat : BaseRichFormat
 24     {
 25         public override void SetFormat(RichTextBox rtbInfo)
 26         {
 27             Font oldFont = rtbInfo.SelectionFont;
 28             Font newFont;
 29             if (oldFont.Bold)
 30             {
 31                 newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Bold);//支持位於運算
 32             }
 33             else
 34             {
 35                 newFont = new Font(oldFont, oldFont.Style | FontStyle.Bold);
 36             }
 37             rtbInfo.SelectionFont = newFont;
 38         }
 39     }
 40 
 41     /// <summary>
 42     /// 斜體
 43     /// </summary>
 44     public class ItalicRichFormat : BaseRichFormat
 45     {
 46         public override void SetFormat(RichTextBox rtbInfo)
 47         {
 48             Font oldFont = rtbInfo.SelectionFont;
 49             Font newFont;
 50             if (oldFont.Italic)
 51             {
 52                 newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Italic);
 53             }
 54             else
 55             {
 56                 newFont = new Font(oldFont, oldFont.Style | FontStyle.Italic);
 57             }
 58             rtbInfo.SelectionFont = newFont;
 59             rtbInfo.Focus();
 60         }
 61     }
 62 
 63     /// <summary>
 64     /// 下划線
 65     /// </summary>
 66     public class UnderLineRichFormat : BaseRichFormat
 67     {
 68         public override void SetFormat(RichTextBox rtbInfo)
 69         {
 70             Font oldFont = rtbInfo.SelectionFont;
 71             Font newFont;
 72             if (oldFont.Underline)
 73             {
 74                 newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Underline);
 75             }
 76             else
 77             {
 78                 newFont = new Font(oldFont, oldFont.Style | FontStyle.Underline);
 79             }
 80             rtbInfo.SelectionFont = newFont;
 81             rtbInfo.Focus();
 82         }
 83     }
 84 
 85     /// <summary>
 86     /// 刪除線
 87     /// </summary>
 88     public class StrikeLineRichFormat : BaseRichFormat
 89     {
 90         public override void SetFormat(RichTextBox rtbInfo)
 91         {
 92             Font oldFont = rtbInfo.SelectionFont;
 93             Font newFont;
 94             if (oldFont.Underline)
 95             {
 96                 newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Strikeout);
 97             }
 98             else
 99             {
100                 newFont = new Font(oldFont, oldFont.Style | FontStyle.Strikeout);
101             }
102             rtbInfo.SelectionFont = newFont;
103             rtbInfo.Focus();
104         }
105     }
106 
107     /// <summary>
108     /// 左對齊
109     /// </summary>
110     public class LeftRichFormat : BaseRichFormat
111     {
112         public override void SetFormat(RichTextBox rtbInfo)
113         {
114             rtbInfo.SelectionAlignment = HorizontalAlignment.Left;
115             rtbInfo.Focus();
116         }
117     }
118 
119     /// <summary>
120     /// 居中對齊
121     /// </summary>
122     public class CenterRichFormat : BaseRichFormat
123     {
124         public override void SetFormat(RichTextBox rtbInfo)
125         {
126             if (rtbInfo.SelectionAlignment == HorizontalAlignment.Center)
127             {
128                 rtbInfo.SelectionAlignment = HorizontalAlignment.Left;
129             }
130             else
131             {
132                 rtbInfo.SelectionAlignment = HorizontalAlignment.Center;
133             }
134 
135             rtbInfo.Focus();
136         }
137     }
138 
139     /// <summary>
140     /// 右對齊
141     /// </summary>
142     public class RightRichFormat : BaseRichFormat
143     {
144         public override void SetFormat(RichTextBox rtbInfo)
145         {
146             if (rtbInfo.SelectionAlignment == HorizontalAlignment.Right)
147             {
148                 rtbInfo.SelectionAlignment = HorizontalAlignment.Left;
149             }
150             else
151             {
152                 rtbInfo.SelectionAlignment = HorizontalAlignment.Right;
153             }
154 
155             rtbInfo.Focus();
156         }
157     }
158 
159     /// <summary>
160     /// 縮進對齊
161     /// </summary>
162     public class IndentRichFormat : BaseRichFormat
163     {
164         public override void SetFormat(RichTextBox rtbInfo)
165         {
166             //每次以10個像素進行縮進
167             rtbInfo.SelectionIndent = rtbInfo.SelectionIndent + 10;
168             rtbInfo.Focus();
169         }
170     }
171 
172     /// <summary>
173     /// 縮進對齊
174     /// </summary>
175     public class OutIndentRichFormat : BaseRichFormat
176     {
177         public override void SetFormat(RichTextBox rtbInfo)
178         {
179             //每次以10個像素進行縮進
180             rtbInfo.SelectionIndent = rtbInfo.SelectionIndent - 10;
181             rtbInfo.Focus();
182         }
183     }
184 
185     /// <summary>
186     /// 下標
187     /// </summary>
188     public class SubScriptRichFormat : BaseRichFormat
189     {
190         public override void SetFormat(RichTextBox rtbInfo)
191         {
192             if (rtbInfo.SelectionCharOffset < 0)
193             {
194                 rtbInfo.SelectionCharOffset = 0;
195             }
196             else {
197                 rtbInfo.SelectionCharOffset = -5;
198             }
199             rtbInfo.Focus();
200         }
201     }
202 
203     /// <summary>
204     /// 上標
205     /// </summary>
206     public class SuperScriptRichFormat : BaseRichFormat
207     {
208         public override void SetFormat(RichTextBox rtbInfo)
209         {
210             if (rtbInfo.SelectionCharOffset > 0)
211             {
212                 rtbInfo.SelectionCharOffset = 0;
213             }
214             else {
215                 rtbInfo.SelectionCharOffset = 5;
216             }
217             rtbInfo.Focus();
218         }
219     }
220 
221     /// <summary>
222     /// 字體
223     /// </summary>
224     public class FontRichFormat : BaseRichFormat
225     {
226         public override void SetFormat(RichTextBox rtbInfo)
227         {
228             FontDialog f = new FontDialog();
229             if (f.ShowDialog() == DialogResult.OK)
230             {
231                 FontFamily family = f.Font.FontFamily;
232                 rtbInfo.SelectionFont = new Font(family, rtbInfo.SelectionFont.Size, rtbInfo.SelectionFont.Style);
233             }
234             rtbInfo.Focus();
235         }
236     }
237 
238     /// <summary>
239     /// 文本顏色
240     /// </summary>
241     public class ForeColorRichFormat : BaseRichFormat
242     {
243         public override void SetFormat(RichTextBox rtbInfo)
244         {
245             ColorDialog f = new ColorDialog();
246             if (f.ShowDialog() == DialogResult.OK)
247             {
248 
249                 rtbInfo.SelectionColor = f.Color;
250             }
251             rtbInfo.Focus();
252         }
253     }
254 
255     /// <summary>
256     /// 文本背景顏色
257     /// </summary>
258     public class BgColorRichFormat : BaseRichFormat
259     {
260         public override void SetFormat(RichTextBox rtbInfo)
261         {
262             ColorDialog f = new ColorDialog();
263             if (f.ShowDialog() == DialogResult.OK)
264             {
265 
266                 rtbInfo.SelectionBackColor = f.Color;
267             }
268             rtbInfo.Focus();
269         }
270     }
271 
272     /// <summary>
273     /// UL列表,項目符號樣式
274     /// </summary>
275     public class UlRichFormat : BaseRichFormat
276     {
277         public override void SetFormat(RichTextBox rtbInfo)
278         {
279             if (rtbInfo.SelectionBullet)
280             {
281                 rtbInfo.SelectionBullet = false;
282             }
283             else {
284                 rtbInfo.SelectionBullet = true;
285                 rtbInfo.BulletIndent = 10;
286             }
287             rtbInfo.Focus();
288         }
289     }
290 
291     /// <summary>
292     /// 圖片插入
293     /// </summary>
294     public class PicRichFormat : BaseRichFormat
295     {
296         public override void SetFormat(RichTextBox rtbInfo)
297         {
298             OpenFileDialog o = new OpenFileDialog();
299             o.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
300             o.Title = "請選擇圖片";
301             o.Filter = "jpeg|*.jpeg|jpg|*.jpg|png|*.png|gif|*.gif"; 
302             if (o.ShowDialog() == DialogResult.OK) {
303                 string fileName = o.FileName;
304                 try
305                 {
306                    Image bmp = Image.FromFile(fileName);
307                    Clipboard.SetDataObject(bmp);
308 
309                     DataFormats.Format dataFormat = DataFormats.GetFormat(DataFormats.Bitmap);
310                     if (rtbInfo.CanPaste(dataFormat))
311                     {
312                         rtbInfo.Paste(dataFormat);
313                     }
314                         
315                 }
316                 catch (Exception exc)
317                 {
318                     MessageBox.Show("圖片插入失敗。" + exc.Message, "提示",
319                                     MessageBoxButtons.OK, MessageBoxIcon.Information);
320                 }
321 
322             }
323             rtbInfo.Focus();
324         }
325     }
326 
327     /// <summary>
328     /// 刪除
329     /// </summary>
330     public class DelRichFormat : BaseRichFormat
331     {
332         public override void SetFormat(RichTextBox rtbInfo)
333         {
334             rtbInfo.SelectedText = "";
335             rtbInfo.Focus();
336         }
337     }
338 
339     /// <summary>
340     /// 查找
341     /// </summary>
342     public class SearchRichFormat : BaseRichFormat
343     {
344         public override void SetFormat(RichTextBox rtbInfo)
345         {
346             string find = rtbInfo.Tag.ToString();
347             int index=  rtbInfo.Find(find, 0,RichTextBoxFinds.None);
348             int startPos = index;
349             int nextIndex = 0;
350             while (nextIndex != startPos)//循環查找字符串,並用藍色加粗12號Times New Roman標記之  
351             {
352                 rtbInfo.SelectionStart = index;
353                 rtbInfo.SelectionLength = find.Length;
354                 rtbInfo.SelectionColor = Color.Blue;
355                 rtbInfo.SelectionFont = new Font("Times New Roman", (float)12, FontStyle.Bold);
356                 rtbInfo.Focus();
357                 nextIndex = rtbInfo.Find(find, index + find.Length, RichTextBoxFinds.None);
358                 if (nextIndex == -1)//若查到文件末尾,則充值nextIndex為初始位置的值,使其達到初始位置,順利結束循環,否則會有異常。  
359                 {
360                     nextIndex = startPos;
361                 }
362                 index = nextIndex;
363             }
364             rtbInfo.Focus();
365         }
366     }
367 
368     /// <summary>
369     /// 打印
370     /// </summary>
371     public class PrintRichFormat : BaseRichFormat
372     {
373         private RichTextBox richTextbox;
374 
375         public override void SetFormat(RichTextBox rtbInfo)
376         {
377             this.richTextbox = rtbInfo;
378             PrintDocument pd = new PrintDocument();
379             pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
380             // 打印文檔
381             pd.Print();
382         }
383 
384         private void pd_PrintPage(object sender, PrintPageEventArgs ev)
385         {
386             //ev.Graphics.DrawString(richTextbox.Text);
387             //ev.HasMorePages = true;
388         }
389     }
390 
391     /// <summary>
392     /// 字體大小
393     /// </summary>
394     public class FontSizeRichFormat : BaseRichFormat
395     {
396         public override void SetFormat(RichTextBox rtbInfo)
397         {
398             string fontSize = rtbInfo.Tag.ToString();
399             float fsize = 0.0f;
400             if (float.TryParse(fontSize, out fsize)) {
401                 rtbInfo.SelectionFont = new Font(rtbInfo.Font.FontFamily, fsize, rtbInfo.SelectionFont.Style);
402             }
403             rtbInfo.Focus();
404         }
405     }
406 }
View Code

頁面代碼【由於實現了代碼封裝,所有頁面代碼較少】

 1 using DemoRichText.Model;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.ComponentModel;
 5 using System.Data;
 6 using System.Drawing;
 7 using System.Linq;
 8 using System.Text;
 9 using System.Threading.Tasks;
10 using System.Windows.Forms;
11 
12 namespace DemoRichText
13 {
14     public partial class MainForm : Form
15     {
16         public MainForm()
17         {
18             InitializeComponent();
19         }
20         
21 
22         public void btnButtonClick(object sender, EventArgs e) {
23             Button btn = (Button)sender;
24             BTNType btnType;
25             if (Enum.TryParse<BTNType>(btn.Tag.ToString(), out btnType)) {
26                 if (btnType == BTNType.Search) {
27                     if (!string.IsNullOrEmpty(this.txtSearch.Text.Trim()))
28                     {
29                         this.rtbInfo.Tag = this.txtSearch.Text.Trim();
30                     }
31                     else {
32                         return;
33                     }
34                     
35                 }
36                 IRichFormat richFomat = RichFormatFactory.CreateRichFormat(btnType);
37                 richFomat.SetFormat(this.rtbInfo);
38             }
39         }
40 
41         private void combFontSize_SelectedIndexChanged(object sender, EventArgs e)
42         {
43             float fsize = 12.0f;
44             if (combFontSize.SelectedIndex > -1) {
45                 if (float.TryParse(combFontSize.SelectedItem.ToString(), out fsize)) {
46                     rtbInfo.Tag = fsize.ToString();
47                     IRichFormat richFomat = RichFormatFactory.CreateRichFormat(BTNType.FontSize);
48                     richFomat.SetFormat(this.rtbInfo);
49                 }
50                 return;
51             }
52         }
53     }
54 }
View Code


RichTextBox是一個功能豐富的控件,值得學習。

源碼下載鏈接

源碼鏈接

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM