【发布时间】:2011-07-16 14:29:50
【问题描述】:
我有一个富文本框,其中可能包含一个包含粗体、斜体甚至不同字体和大小元素的字符串。如果我选择了整个字符串,包括所有的差异,我怎样才能在不将整个字符串转换为只有“粗体”属性的通用字体的情况下“加粗”该字符串?
例如:我想把“This is some text”变成“This is some text”
请注意,“is some”仍然是斜体,“text”仍然是不同的字体。
我目前拥有的非常简单:
private void tsBold_Click(object sender, EventArgs e)
{
if (rtb.SelectionFont == null) return;
Font f;
if (tsBold.Checked)
f = new Font(rtb.SelectionFont, FontStyle.Bold);
else
f = new Font(rtb.SelectionFont, FontStyle.Regular);
rtb.SelectionFont = f;
rtb.Focus();
}
当然,这会将完全相同的字体应用于整个选择。有什么方法可以将“粗体”附加到现有字体?
回答 虽然下面的“官方”答案只是冰山一角,但这是我在正确方向上需要的推动力。谢谢你的提示。
这是我的官方修复:
我将此添加到我的 RichTextBox 对象中:
/// <summary>
/// Change the richtextbox style for the current selection
/// </summary>
public void ChangeFontStyle(FontStyle style, bool add)
{
//This method should handle cases that occur when multiple fonts/styles are selected
// Parameters:-
// style - eg FontStyle.Bold
// add - IF true then add else remove
// throw error if style isn't: bold, italic, strikeout or underline
if (style != FontStyle.Bold
&& style != FontStyle.Italic
&& style != FontStyle.Strikeout
&& style != FontStyle.Underline)
throw new System.InvalidProgramException("Invalid style parameter to ChangeFontStyle");
int rtb1start = this.SelectionStart;
int len = this.SelectionLength;
int rtbTempStart = 0;
//if len <= 1 and there is a selection font then just handle and return
if (len <= 1 && this.SelectionFont != null)
{
//add or remove style
if (add)
this.SelectionFont = new Font(this.SelectionFont, this.SelectionFont.Style | style);
else
this.SelectionFont = new Font(this.SelectionFont, this.SelectionFont.Style & ~style);
return;
}
using (EnhancedRichTextBox rtbTemp = new EnhancedRichTextBox())
{
// Step through the selected text one char at a time
rtbTemp.Rtf = this.SelectedRtf;
for (int i = 0; i < len; ++i)
{
rtbTemp.Select(rtbTempStart + i, 1);
//add or remove style
if (add)
rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style | style);
else
rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style & ~style);
}
// Replace & reselect
rtbTemp.Select(rtbTempStart, len);
this.SelectedRtf = rtbTemp.SelectedRtf;
this.Select(rtb1start, len);
}
return;
}
然后我将点击方法更改为使用以下模式:
private void tsBold_Click(object sender, EventArgs e)
{
enhancedRichTextBox1.ChangeFontStyle(FontStyle.Bold, tsBold.Checked);
enhancedRichTextBox1.Focus();
}
【问题讨论】:
-
为什么这在 WinForms 中这么难?在 Win32 级别,这是一个微不足道的
EM_SETCHARFORMAT。既然你手头有窗把手,你就不能那样做吗? -
请不要将答案发布为对您问题的更新。您可以自行回答自己的问题。此外,这样人们就可以为您的答案投票。
标签: c# .net winforms richtextbox