[英]Reset RTF in RichTextBox?
我正在嘗試“重置”我的RichTextBox格式(WinForms,而不是WPF)。 我以前用過
richTextBox.Text = 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中文本的格式而不清除上面示例中的文本(因為這會產生不希望的閃爍)?
可悲的是,我已盡最大努力將其減少到只需要的代碼。 它仍然很大,但它會起作用。 .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;
編輯::
一定要插入評論,說明你為什么要做你正在做的事情。 對於不知不覺,它看起來很荒謬。
只是使用:
richTextBox1.Clear();
......應該做的伎倆。 適合我。
有一段時間,我一直在自己的程序中使用這段代碼。 它直接設置RichTextBox的RTF,因此應該比通常的方式設置樣式快得多。 它接受一個字符串(主文本),並且可選地還采用Color數組,字體大小數組(int)和font-weight數組(bool),每個數組代表每個字符的每個顏色,大小或字體權重。字符串。
或者,您可以簡單地保留標題給出的默認大小,重量和斜體數字。
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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.