如何制作RichTextBox文本?

可能重复:
如何防止richTextBox在其中粘贴图像?

如果您使用的是RichtextboxRichtextbox中有几个优点,例如:

我们可以在上面使用彩色字体

在区域中设置自定义字体

附上文件..等等

看看图片: 在此处输入图像描述

这是我的问题:

我可以只制作文字吗?

在我的项目中,根本不需要附加文件等。 我甚至不想在其上附加或粘贴图像,我只想在Richtextbox上使用“仅文本”

我怎样才能做到这一点?

由于RichTextBox没有图像或对象集合,因此您必须使用RTF格式代码。 RichTextBox的所有数据都以纯文本forms存储,并带有特殊格式代码,控件通过其RTF属性公开。 如果您想要阅读或更改它,学习此代码语言是必不可少的,学习资源可以在整个Web上轻松获得,请参阅此概述。 RichTextBox比几个全function编辑器(如MS Word等)使用更简化的rtf代码,因此在操作数据之前将数据加载到RTB通常是有益的,这将消除大量冗余数据。

长话短说,我发现有必要搜索以“pict”或“object”命令开头的rtf组。 知道组可能是嵌套的,你不能只从那里找到第一个端组char,你必须通过char解析字符串char,同时保持分组计数以找到这些组的结尾。 现在您有足够的信息来删除字符串的那一部分。 Rtf可能包含多个图片/对象组,因此您必须执行此操作,直到删除所有图片/对象组。 这是一个示例函数,在删除这些组后返回rtf字符串:

 private string removeRtfObjects(string rtf) { //removing {\pict or {\object groups string pattern = "\\{\\\\pict|\\{\\\\object"; Match m = Regex.Match(rtf, pattern); while (m.Success) { int count = 1; for (int i = m.Index + 2; i <= rtf.Length; i++) { //start group if (rtf(i) == '{') { count += 1; //end group } else if (rtf(i) == '}') { count -= 1; } //found end of pict/object group if (count == 0) { rtf = rtf.Remove(m.Index, i - m.Index + 1); break; // TODO: might not be correct. Was : Exit For } } m = Regex.Match(rtf, pattern); //go again } return rtf; } 

什么时候应该这样做? 你已经提到了Paste,还有Insert,这些可以被KeyDown事件捕获,你可以获得剪贴板信息并相应地处理它。 当您自己处理操作时设置e.Handled = True表示控件不应对此组合键执行任何默认处理。 这也是您在不破坏用户剪贴板的情况下阻止粘贴图像的方法。 例:

 private void RichTextBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { //aware of Paste or Insert if (e.Control && e.KeyCode == Keys.V || e.Shift && e.KeyCode == Keys.I) { if (Clipboard.ContainsImage || Clipboard.ContainsFileDropList) { //some images are transferred as filedrops e.Handled = true; //stops here } else if (Clipboard.ContainsData(DataFormats.Rtf)) { RichTextBox rtbox = new RichTextBox(); //use a temp box to validate/simplify rtbox.Rtf = Clipboard.GetData(DataFormats.Rtf); this.RichTextBox1.SelectedRtf = this.removeRtfObjects(rtbox.Rtf); rtbox.Dispose(); e.Handled = true; } } } 

对的,这是可能的。

在RichTextBox1_KeyDown中处理Ctrl + V,然后检查剪贴板中的数据格式:如果数据是纯文本,则粘贴它; 如果数据是RTF,将其转换为纯文本(在缓冲区中而不更改剪贴板内容)并粘贴它; 不要粘贴任何其他类型的数据。

这是一个部分示例,只是为了向您展示如何继续:

 private void richTextBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.V) { // suspend layout to avoid blinking richTextBox2.SuspendLayout(); // get insertion point int insPt = richTextBox2.SelectionStart; // preserve text from after insertion pont to end of RTF content string postRTFContent = richTextBox2.Text.Substring(insPt); // remove the content after the insertion point richTextBox2.Text = richTextBox2.Text.Substring(0, insPt); // add the clipboard content and then the preserved postRTF content richTextBox2.Text += (string)Clipboard.GetData("Text") + postRTFContent; // adjust the insertion point to just after the inserted text richTextBox2.SelectionStart = richTextBox2.TextLength - postRTFContent.Length; // restore layout richTextBox2.ResumeLayout(); // cancel the paste e.Handled = true; } }