C# RichTextBox 制作文本编辑器

≯℡__Kan透↙ 提交于 2019-12-25 01:28:40

本文利用一个简单的小例子【文本编辑器】,讲解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是一个功能丰富的控件,值得学习。

源码下载链接

源码链接

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!