如何在C#中的富文本框中使某些文本变为粗体
我想创建一个文本编辑器,我可以使文本变粗,改变颜色等。
我发现这段代码大致有效:
public static void BoldSelectedText(RichTextBox control) { control.SelectionFont = new Font(control.Font.FontFamily, control.Font.Size, FontStyle.Bold); }
但是当我在RichTextBox
输入更多字母时,文本仍然是粗体。
除非我选择文本并点击“Make Bold”按钮,否则我怎样才能使所选文本只是粗体而下一个字符不是?
您应该在选择后将字体设置为原始字体。
如果需要,可以保存SelectionStart
和SelectionLength
并调用Select
方法再次选择文本。
// 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);
这样文本保持选中状态,之后的字体仍然正确。