我想创建一个文本编辑器,我可以使文本变粗,改变颜色等。
我发现这段代码大致有效:
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);
这样文本保持选中状态,之后的字体仍然正确。
您应该在选择后将字体设置为原始字体。
如果你想要你可以保存 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);
这样文本保持选中状态,之后的字体仍然正确。