如何在C#中的富文本框中使某些文本变为粗体 [英] How to make some text bold in a rich text box in C#
问题描述
我想创建一个文本编辑器,在其中可以使文本加粗,更改其颜色等。
I want to create a text editor where I can make text bold, change its color, etc.
我发现此代码可以正常工作:
I found this code to approximately work:
public static void BoldSelectedText(RichTextBox control)
{
control.SelectionFont = new Font(control.Font.FontFamily, control.Font.Size, FontStyle.Bold);
}
但是当我在 RichTextBox中键入更多字母时
文本仍为粗体。
But when I type in more letters in the RichTextBox
the text is still bold.
如何使文本变为仅选中的文本为粗体,而下一个字符为非选择文本并单击使粗体按钮?
How can I make it so that only the selected text is bold and the next characters aren't unless I select the text and hit the "Make Bold" button?
推荐答案
您应在选择后将字体设置为原始字体。
You should set the font after the selection to the original font.
如果需要,可以保存 SelectionStart
和 SelectionLength
,然后调用 Select
方法再次选择文本。
If you want you can save the SelectionStart
and SelectionLength
and call the Select
method to select the text again.
// Remember selection
int selstart = control.SelectionStart;
int sellength = control.SelectionLength;
// Set font of selected text
// You can use FontStyle.Bold | FontStyle.Italic to apply more than one style
control.SelectionFont = new Font(control.Font, FontStyle.Bold);
// Set cursor after selected text
control.SelectionStart = control.SelectionStart + control.SelectionLength;
control.SelectionLength = 0;
// Set font immediately after selection
control.SelectionFont = control.Font;
// Reselect previous text
control.Select(selstart, sellength);
这样,文本保持选中状态,并且之后的字体仍然正确。
this way the text stays selected, and the font afterwards is still correct.
这篇关于如何在C#中的富文本框中使某些文本变为粗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!