C# 如何在不更改样式的情况下设置RichTextBox.SelectionFont FontFamily?

C# 如何在不更改样式的情况下设置RichTextBox.SelectionFont FontFamily?,c#,.net,richtextbox,rtf,C#,.net,Richtextbox,Rtf,我的应用程序中的一个控件限制用户只能更改文本的字体样式(B、I、U)和颜色。为此,我创建了一个从RichTextBox继承的自定义控件。我可以截取CTRL-V,并将粘贴文本的字体设置为systemfont.DefaultFont。我目前面临的问题是,如果粘贴的文本包含,例如,半粗体半常规样式-粗体丢失 也就是说,“FooBar”只会粘贴为“Foo-Bar” 我目前唯一的想法是逐个字符(非常慢)浏览文本,并执行以下操作: public class MyRichTextBox : RichTextB

我的应用程序中的一个控件限制用户只能更改文本的字体样式(B、I、U)和颜色。为此,我创建了一个从RichTextBox继承的自定义控件。我可以截取CTRL-V,并将粘贴文本的字体设置为
systemfont.DefaultFont
。我目前面临的问题是,如果粘贴的文本包含,例如,半粗体半常规样式-粗体丢失

也就是说,“FooBar”只会粘贴为“Foo-Bar”

我目前唯一的想法是逐个字符(非常慢)浏览文本,并执行以下操作:

public class MyRichTextBox : RichTextBox
{

private RichTextBox hiddenBuffer = new RichTextBox();

/// <summary>
/// This paste will strip the font size, family and alignment from the text being pasted.
/// </summary>
public void PasteUnformatted()
{
    this.hiddenBuffer.Clear();
    this.hiddenBuffer.Paste();

    for (int x = 0; x < this.hiddenBuffer.TextLength; x++)
    {
        // select the next character
        this.hiddenBuffer.Select(x, 1);

        // Set the font family and size to default
        this.hiddenBuffer.SelectionFont = new Font(SystemFonts.DefaultFont.FontFamily, SystemFonts.DefaultFont.Size, this.hiddenBuffer.SelectionFont.Style);
    }

    // Reset the alignment
    this.hiddenBuffer.SelectionAlignment = HorizontalAlignment.Left;

    base.SelectedRtf = this.hiddenBuffer.SelectedRtf;
    this.hiddenBuffer.Clear();
}
公共类MyRichTextBox:RichTextBox
{
private RichTextBox hiddenBuffer=new RichTextBox();
/// 
///此粘贴将从粘贴的文本中删除字体大小、系列和对齐方式。
/// 
公共无效粘贴未格式化()
{
this.hiddenBuffer.Clear();
this.hiddenBuffer.Paste();
对于(int x=0;x
}


有人能想出一个更干净(更快)的解决方案吗?

MSDN论坛上的“nobugz”帮我回答了这个问题(我很快就需要答案,所以在经历了差不多一天的风滚草风滚草之后,我不得不去别处看看——不要评判我!)


对于那些想要德尔菲答案的人,请提供一份摘录,让您了解基本想法:

using RichEdit; //reqd. for the constants and types

var
  chformat : TCharFormat2;
  fontname : string;

begin
  FillChar(chformat,sizeof(chformat),0);
  chformat.cbSize := sizeof(chformat);
  //only modify the szFaceName field, height etc. left alone
  chformat.dwMask :=  CFM_FACE; 
  //get the fontname set by the user
  fontname := AdvFontSelector1.Text;
  strpcopy(chformat.szFaceName,fontname);
  RichEdit1.Perform(EM_SETCHARFORMAT, SCF_SELECTION, lparam(@chformat));
end;
using RichEdit; //reqd. for the constants and types

var
  chformat : TCharFormat2;
  fontname : string;

begin
  FillChar(chformat,sizeof(chformat),0);
  chformat.cbSize := sizeof(chformat);
  //only modify the szFaceName field, height etc. left alone
  chformat.dwMask :=  CFM_FACE; 
  //get the fontname set by the user
  fontname := AdvFontSelector1.Text;
  strpcopy(chformat.szFaceName,fontname);
  RichEdit1.Perform(EM_SETCHARFORMAT, SCF_SELECTION, lparam(@chformat));
end;