如何在不更改样式的情况下设置 RichTextBox.SelectionFont FontFamily?
我的应用程序中的控件之一限制用户只能更改文本的字体样式(B、I、U)和颜色。为此,我创建了一个继承自 RichTextBox 的自定义控件。我能够拦截 CTRL-V,并将粘贴文本的字体设置为 SystemFonts.DefaultFont。我当前面临的问题是,如果粘贴的文本包含例如一半粗体一半常规样式 - 粗体就会丢失。
即“Foo Bar”将仅粘贴为“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();
}
}
有人能想到更干净(更快)的解决方案吗?
One of the controls in my application limits a user to be able to change only the font style (B, I, U) and colour of the text. I have created a custom control which inherits from the RichTextBox for this purpose. I am able to intercept CTRL-V, and set the font of the pasted text to SystemFonts.DefaultFont
. The problem I am currently facing is if the pasted text contains, for example, half bold half regular style - the bold is lost.
I.e. "Foo Bar" will just paste as "Foo Bar".
My only idea currently is to go through the text character by character (very slow), and do something like:
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();
}
}
Can anyone think of a cleaner (and faster) solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MSDN 论坛上的“nobugz”为我回答了这个问题(我需要快速得到答案,所以在经历了近一天的风滚草之后,我不得不去其他地方寻找 - 不要评判我!):
'nobugz' over on the MSDN Forums answered this for me (I needed an answer quickly, so after almost a day of tumbleweed from SO, I had to look elsewhere - don't judge me!):
对于那些想要 Delphi 答案的人,摘录可以为您提供基本概念:
For those wanting a Delphi answer, an extract to give you the basic idea: