我想在我的RichTextBox中(的WinForms,而不是WPF)“重置”的格式。我以前使用

richTextBox.Text = richTextBox.Text;

但是,好像突然让我失望。现在,不管我设置richTextBox.Text到,它保留了一些的RTF格式的。

我试图

richTextBox.Rtf = richTextBox.Text;

然而,抱怨一个不正确的格式。有一定有更好的方法来做到这一点。 (当然,选择了整个事情,然后重新设置背景色,前景色和字体的作品,但在闪烁作为整个事情的结果被选中,那么取消,再加上它的速度较慢,需要更多的代码。)任何人有任何想法?

编辑: 我已经得到这个工作:

string tempTxt = richTextBox.Text;
richTextBox.Clear();
richTextBox.Text = tempTxt;

但必须有一个更好的办法,对吧?

编辑2: 需要明确的是,我要删除所有格式,同时保留文本。它看起来像在第一编辑将推出的代码,除非其他人有更有效的/更好的编码方式。

修改3:

richTextBox.Text = richTextBox.Text.ToString();

似乎并没有工作,因为它仍然无法清除所有格式。上面我不喜欢在第一个编辑方法的原因是它使文本框中输入“闪光”时,它会清除它,然后再输入文字。这好像应该仅仅是一个richTextBox.ResetFormatting()方法,或某种方式来访问相同的功能,如Clear()方法清楚地(没有双关语意)确实某种除了格式化复位简单地清除所有文本

要总结:

<强>有一种方法(并且如果是这样,它是什么)来重置在RichTextBox的文本的格式而不清除文本如在上面的例子中(因为产生不希望的闪烁)吗

有帮助吗?

解决方案

Saddly我已经做了我最好的努力,苗条下来,只需要的代码。它仍然是很大的,但它会奏效。在.NET中的RichTextBox的API是非常有限的,做任何事情,你几乎要咚到Win32的库。我已经建立了解决这个事情整个库,这样我可以切换大胆,并确定是否大胆实际上是整个选择集。

<强>用法:

RichTextBox te = ...;
te.ClearAllFormatting(new Font("Microsoft Sans Serif", 8.25f));

<强>的代码吨

static class RichTextExtensions
{
    public static void ClearAllFormatting(this RichTextBox te, Font font)
    {
        CHARFORMAT2 fmt = new CHARFORMAT2();

        fmt.cbSize = Marshal.SizeOf(fmt);
        fmt.dwMask = CFM_ALL2;
        fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
        fmt.szFaceName = font.FontFamily.Name;

        double size = font.Size;
        size /= 72;//logical dpi (pixels per inch)
        size *= 1440.0;//twips per inch

        fmt.yHeight = (int)size;//165
        fmt.yOffset = 0;
        fmt.crTextColor = 0;
        fmt.bCharSet = 1;// DEFAULT_CHARSET;
        fmt.bPitchAndFamily = 0;// DEFAULT_PITCH;
        fmt.wWeight = 400;// FW_NORMAL;
        fmt.sSpacing = 0;
        fmt.crBackColor = 0;
        //fmt.lcid = ???
        fmt.dwMask &= ~CFM_LCID;//don't know how to get this...
        fmt.dwReserved = 0;
        fmt.sStyle = 0;
        fmt.wKerning = 0;
        fmt.bUnderlineType = 0;
        fmt.bAnimation = 0;
        fmt.bRevAuthor = 0;
        fmt.bReserved1 = 0;

        SendMessage(te.Handle, EM_SETCHARFORMAT, SCF_ALL, ref fmt);
    }

    private const UInt32 WM_USER = 0x0400;
    private const UInt32 EM_GETCHARFORMAT = (WM_USER + 58);
    private const UInt32 EM_SETCHARFORMAT = (WM_USER + 68);
    private const UInt32 SCF_ALL = 0x0004;
    private const UInt32 SCF_SELECTION = 0x0001;

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, UInt32 wParam, ref CHARFORMAT2 lParam);

    [StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)]
    struct CHARFORMAT2
    {
        public int cbSize;
        public uint dwMask;
        public uint dwEffects;
        public int yHeight;
        public int yOffset;
        public int crTextColor;
        public byte bCharSet;
        public byte bPitchAndFamily;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
        public string szFaceName;
        public short wWeight;
        public short sSpacing;
        public int crBackColor;
        public int lcid;
        public int dwReserved;
        public short sStyle;
        public short wKerning;
        public byte bUnderlineType;
        public byte bAnimation;
        public byte bRevAuthor;
        public byte bReserved1;
    }

    #region CFE_
    // CHARFORMAT effects 
    const UInt32 CFE_BOLD = 0x0001;
    const UInt32 CFE_ITALIC = 0x0002;
    const UInt32 CFE_UNDERLINE = 0x0004;
    const UInt32 CFE_STRIKEOUT = 0x0008;
    const UInt32 CFE_PROTECTED = 0x0010;
    const UInt32 CFE_LINK = 0x0020;
    const UInt32 CFE_AUTOCOLOR = 0x40000000;            // NOTE: this corresponds to 
    // CFM_COLOR, which controls it 
    // Masks and effects defined for CHARFORMAT2 -- an (*) indicates
    // that the data is stored by RichEdit 2.0/3.0, but not displayed
    const UInt32 CFE_SMALLCAPS = CFM_SMALLCAPS;
    const UInt32 CFE_ALLCAPS = CFM_ALLCAPS;
    const UInt32 CFE_HIDDEN = CFM_HIDDEN;
    const UInt32 CFE_OUTLINE = CFM_OUTLINE;
    const UInt32 CFE_SHADOW = CFM_SHADOW;
    const UInt32 CFE_EMBOSS = CFM_EMBOSS;
    const UInt32 CFE_IMPRINT = CFM_IMPRINT;
    const UInt32 CFE_DISABLED = CFM_DISABLED;
    const UInt32 CFE_REVISED = CFM_REVISED;

    // CFE_AUTOCOLOR and CFE_AUTOBACKCOLOR correspond to CFM_COLOR and
    // CFM_BACKCOLOR, respectively, which control them
    const UInt32 CFE_AUTOBACKCOLOR = CFM_BACKCOLOR;
    #endregion
    #region CFM_
    // CHARFORMAT masks 
    const UInt32 CFM_BOLD = 0x00000001;
    const UInt32 CFM_ITALIC = 0x00000002;
    const UInt32 CFM_UNDERLINE = 0x00000004;
    const UInt32 CFM_STRIKEOUT = 0x00000008;
    const UInt32 CFM_PROTECTED = 0x00000010;
    const UInt32 CFM_LINK = 0x00000020;         // Exchange hyperlink extension 
    const UInt32 CFM_SIZE = 0x80000000;
    const UInt32 CFM_COLOR = 0x40000000;
    const UInt32 CFM_FACE = 0x20000000;
    const UInt32 CFM_OFFSET = 0x10000000;
    const UInt32 CFM_CHARSET = 0x08000000;

    const UInt32 CFM_SMALLCAPS = 0x0040;            // (*)  
    const UInt32 CFM_ALLCAPS = 0x0080;          // Displayed by 3.0 
    const UInt32 CFM_HIDDEN = 0x0100;           // Hidden by 3.0 
    const UInt32 CFM_OUTLINE = 0x0200;          // (*)  
    const UInt32 CFM_SHADOW = 0x0400;           // (*)  
    const UInt32 CFM_EMBOSS = 0x0800;           // (*)  
    const UInt32 CFM_IMPRINT = 0x1000;          // (*)  
    const UInt32 CFM_DISABLED = 0x2000;
    const UInt32 CFM_REVISED = 0x4000;

    const UInt32 CFM_BACKCOLOR = 0x04000000;
    const UInt32 CFM_LCID = 0x02000000;
    const UInt32 CFM_UNDERLINETYPE = 0x00800000;        // Many displayed by 3.0 
    const UInt32 CFM_WEIGHT = 0x00400000;
    const UInt32 CFM_SPACING = 0x00200000;      // Displayed by 3.0 
    const UInt32 CFM_KERNING = 0x00100000;      // (*)  
    const UInt32 CFM_STYLE = 0x00080000;        // (*)  
    const UInt32 CFM_ANIMATION = 0x00040000;        // (*)  
    const UInt32 CFM_REVAUTHOR = 0x00008000;

    const UInt32 CFE_SUBSCRIPT = 0x00010000;        // Superscript and subscript are 
    const UInt32 CFE_SUPERSCRIPT = 0x00020000;      //  mutually exclusive           

    const UInt32 CFM_SUBSCRIPT = (CFE_SUBSCRIPT | CFE_SUPERSCRIPT);
    const UInt32 CFM_SUPERSCRIPT = CFM_SUBSCRIPT;

    // CHARFORMAT "ALL" masks
    const UInt32 CFM_EFFECTS = (CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_COLOR |
                         CFM_STRIKEOUT | CFE_PROTECTED | CFM_LINK);
    const UInt32 CFM_ALL = (CFM_EFFECTS | CFM_SIZE | CFM_FACE | CFM_OFFSET | CFM_CHARSET);

    const UInt32 CFM_EFFECTS2 = (CFM_EFFECTS | CFM_DISABLED | CFM_SMALLCAPS | CFM_ALLCAPS
                        | CFM_HIDDEN | CFM_OUTLINE | CFM_SHADOW | CFM_EMBOSS
                        | CFM_IMPRINT | CFM_DISABLED | CFM_REVISED
                        | CFM_SUBSCRIPT | CFM_SUPERSCRIPT | CFM_BACKCOLOR);

    const UInt32 CFM_ALL2 = (CFM_ALL | CFM_EFFECTS2 | CFM_BACKCOLOR | CFM_LCID
                        | CFM_UNDERLINETYPE | CFM_WEIGHT | CFM_REVAUTHOR
                        | CFM_SPACING | CFM_KERNING | CFM_STYLE | CFM_ANIMATION);
    #endregion
}

更多你问?

我使用大多数这通过一个包装此为所有的样式和字体更改的小工具类。这样你就可以改变字体大小,而不是改变字体的名字,等等。

class RichTextStyle
{   
    private readonly Control _textEdit;
    private readonly CHARFORMAT2 _charFormat;

    public RichTextStyle(RichTextBox te)
    {
        _textEdit = te;
        _charFormat = new CHARFORMAT2();
        _charFormat.cbSize = Marshal.SizeOf(_charFormat);
        SendMessage(te.Handle, EM_GETCHARFORMAT, SCF_SELECTION, ref _charFormat);
    }

    private void SetEffect(UInt32 mask, UInt32 effect, bool valid)
    {
        CHARFORMAT2 fmt = new CHARFORMAT2();
        fmt.cbSize = Marshal.SizeOf(fmt);
        fmt.dwMask = mask;
        fmt.dwEffects = valid ? effect : 0;
        SendMessage(_textEdit.Handle, EM_SETCHARFORMAT, SCF_SELECTION, ref fmt);
    }

    private bool GetEffect(UInt32 mask, UInt32 effect)
    {
        return (0 != (_charFormat.dwMask & mask)) && (0 != (_charFormat.dwEffects & effect));
    }

    public bool Bold { get { return GetEffect(CFM_BOLD, CFE_BOLD); } set { SetEffect(CFM_BOLD, CFE_BOLD, value); } }
    public bool Italic { get { return GetEffect(CFM_ITALIC, CFE_ITALIC); } set { SetEffect(CFM_ITALIC, CFE_ITALIC, value); } }

    // ... etc ... etc ... you get the idea.

其他提示

什么
richTextBox.Text = richTextBox.Text.ToString();

我已经使用

var t = richTextBox1.Text;
richTextBox1.Text = t; 

EDIT ::

一定要插入注释,为什么你在做你正在做什么。为了浑然不知,它看起来可笑。

只需使用:

richTextBox1.Clear();

...应该做的伎俩。我的作品。

有一段时间,我一直在用我自己的程序该代码。它直接设置在RichTextBox的RTF,所以应该比设置样式通常的方式快得多。这需要在一个字符串(主要文本),并且可选地还需要一个彩色阵列,字体大小阵列(INT),和字体重量阵列(布尔),其每一个代表了每个字符的每个颜色,大小或字体重量的字符串。

另外,也可以简单地保持默认尺寸,重量,斜体由标题给定的数字。

public string text2RTF(string text, Color[] color = null, bool[] bold = null, int[] size = null,
                        string font = "Microsoft Sans Serif", double defaultFontSize = 16,
                        bool defaultFontBold = false, bool defaultFontItalic = false, char align = 'l')
{
    StringBuilder rtf = new StringBuilder();
    rtf.Append(@"{\rtf1\ansi\ansicpg1252\deff0\deflang2057{\fonttbl{\f0\fnil\fcharset0 ");
    rtf.Append(font);
    rtf.Append(@";}}{\colortbl ;");

    if (color != null)
    {
        rtf.Append("\\red" + (color[0].R).ToString() + "\\green" + (color[0].G).ToString() + "\\blue" + (color[0].B).ToString() + ";");
        for (int i = 1; i < text.Length; i++)
        {
            if ((color[i].R != color[i - 1].R || color[i].G != color[i - 1].G || color[i].B != color[i - 1].B))
            {
                rtf.Append("\\red" + (color[i].R).ToString() + "\\green" + (color[i].G).ToString() + "\\blue" + (color[i].B).ToString() + ";");
            }
        }
    }


    rtf.Append("}\n\\viewkind4\\uc1\\pard");
    if (defaultFontBold == true) rtf.Append("\\b");
    if (defaultFontItalic == true) rtf.Append("\\i");

    if (align == 'r')   rtf.Append("\\qr");

    rtf.Append("\\f0\\fs" + (Math.Round(defaultFontSize)).ToString()+" ");
    int startOfActualText = rtf.Length;

    int count = 1;
    for (int i = 0; i < text.Length; i++)
    {
        if (color!=null && (i == 0 || color[i].R != color[i - 1].R || color[i].G != color[i - 1].G || color[i].B != color[i - 1].B))
        {
            rtf.Append("\\cf"); rtf.Append(count.ToString() + " "); count++;
        }
        if (bold!=null && (i == 0 || bold[i] != bold[i - 1]))
        {
            if (bold[i] == true) rtf.Append("\\b1 ");
            else rtf.Append("\\b0 ");
        }
        if (size!=null && (i == 0 || size[i] != size[i - 1]))
        {
            rtf.Append("\\fs"+size[i].ToString()+" " );                 
        }

        if (text[i] == '\\' || text[i] == '}' || text[i] == '{') rtf.Append('\\');

        // GetRtfUnicodeOfChar:
        string st="";
        if (text[i] <= 0x7f) st = text[i].ToString();
        else st = "\\u" + Convert.ToUInt32(text[i]) + "?";


        rtf.Append(st);
    }

    rtf.Append("\n}");
    rtf.Replace("\n", "\\par\n", startOfActualText, rtf.Length - startOfActualText);


    return rtf.ToString();

}

我看到有很多答案,但我认为还有更简单,简单的方法作为扩展名来清除所有格式:

在我的情况下,我需要明确的格式,并留下一个空RichTextBox,因此,我提出这样的功能:

private void ClearRichTextBox()
{
  this.richTextBox1.ForeColor = Color.Empty;
  this.richTextBox1.BackColor = Color.Empty;
  this.richTextBox1.SelectAll();
  this.richTextBox1.SelectionColor = Color.Empty;
  this.richTextBox1.SelectionBackColor = Color.Empty;
  this.richTextBox1.SelectionFont = this.richTextBox1.Font;
  this.richTextBox1.Clear();
}

然后,简单的解决方案是:

string backUp = this.richTextBox1.Text;
ClearRichTextBox();
this.richTextBox1.Text = backUp;

或者干脆去掉在清除功能的this.richTextBox1.Clear();线。 (这可能也是工作,但我不提供任何保证,因为我测试这只是简单的打印格式,因此它可以是任何其他行应添加删除不同的格式。)

当文本应当不被清除记住存储以前的位置/选择和数据的去格式化后刷新状态。

我发现的另一种方式(和,我已切换到使用,因为它不闪光的那一个)是抓住初始RTF串施加任何格式化之前:

string initialRtf = richTextBox.Rtf;

然后,当我想重新格式化,我可以这样做:

richTextBox.Rtf = initialRtf;

然而,这不是真正的完美,因为它需要的文本保持不变,这样的。嗯,至少它比在问题中详述的方法更好一点。

  

“我不喜欢在第一编辑方法的原因上面它使文本框‘闪’时它清除然后重新输入文本。”

您应该能够实现SuspendLayout()和ResumeLayout()方法。

string tempTxt = richTextBox.Text;
rtbIncludes.SuspendLayout();
richTextBox.Clear();
richTextBox.Text = tempTxt;
rtbIncludes.ResumeLayout();

SuspendLayout()和ResumeLayout()将停止从而你操纵数据绘制的控制。如果操作不采取长,你就能清晰地将文字和分配无格式文本后面没有它看似在屏幕上闪烁。

如果它确实需要太长时间,控制装置将直到ResumeLayout()被调用显示为黑色矩形。

RichTextBox rtbTemp = new RichTextBox();
rtbTemp.Text = rtb.Text;
rtb.Rtf = rtbTemp.Rtf;

希望它的工作原理

工作正常..

var TempString = richTextBox1.Text;
richTextBox1.Rtf = string.Empty;
richTextBox1.Text = TempString ;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top