我在这里也需要同样的东西。而且我没有找到最好的解决方案......所以,这是丑陋的一个。
private void UglyChangeFontSize(RichTextBox rtb, float newSize = -1f, FontFamily fontFamily = null) {
if (rtb.SelectionFont != null) {
if (newSize < 0) newSize = rtb.SelectionFont.Size;
if (fontFamily == null) fontFamily = rtb.SelectionFont.FontFamily;
rtb.SelectionFont = new Font(fontFamily, newSize, rtb.SelectionFont.Style);
}
else {
// Backup Selection
var sel = rtb.SelectionStart;
var selLen = rtb.SelectionLength;
// Change, char by char
for (int k = 0; k < selLen; k++) {
rtb.Select(sel + k, 1);
if (newSize < 0) newSize = rtb.SelectionFont.Size;
var ff = fontFamily ?? rtb.SelectionFont.FontFamily;
rtb.SelectionFont = new Font(fontFamily, newSize, rtb.SelectionFont.Style);
}
// Restore Selection
rtb.SelectionStart = sel;
rtb.SelectionLength = selLen;
}
}
改进版
这是一个更好的版本,它包括:
- 禁用 RichTextBox 绘图(更改字体时);
- 防止“逐字符修改”进入撤消/重做堆栈;
- 执行更改时显示 WaitCursor。
要求
- External.cs
- RichOLE.cs
-
(Optional) RicherTextBox -- 我围绕这个构建了我的代码,这是构建一个类似写字板的项目的一个很好的开始
代码
RichTextBox myRichTextBox = new RichTextBox();
RichOLE mRichOle = new RichOLE(myRichTextBox);
...
private void UglyChangeFontSize(RichTextBox rtb, float newSize = -1f, FontFamily fontFamily = null) {
if (rtb.SelectionFont != null) {
if (newSize < 0) newSize = rtb.SelectionFont.Size;
if (fontFamily == null) fontFamily = rtb.SelectionFont.FontFamily;
rtb.SelectionFont = new Font(fontFamily, newSize, rtb.SelectionFont.Style);
}
else {
Cursor = Cursors.WaitCursor;
// Hide the modifications from the user
External.LockWindowAndKeepScrollPosition(rtb, () =>
{
// Backup Selection
var sel = rtb.SelectionStart;
var selLen = rtb.SelectionLength;
// Disable UNDO for this "in pieces modifications" [START]
rtb.SelectedRtf = rtb.SelectedRtf; // Required to allow Undo
//mFontLockEvents = true; // RicherTextBox
mRichOle.EnableUndo(false);
// Disable UNDO for this "in pieces modifications" [END]
// Change, char by char
for (int k = 0; k < selLen; k++) {
rtb.Select(sel + k, 1);
// again, ugly... buuut we have Branch Prediction (google it)
if (newSize < 0) newSize = rtb.SelectionFont.Size;
var ff = fontFamily ?? rtb.SelectionFont.FontFamily;
rtb.SelectionFont = new Font(fontFamily, newSize, rtb.SelectionFont.Style);
}
// Disable UNDO for this "in pieces modifications" [START]
//mFontLockEvents = false; // RicherTextBox
mRichOle.EnableUndo(true);
// Disable UNDO for this "in pieces modifications" [END]
// Restore Selection
rtb.SelectionStart = sel;
rtb.SelectionLength = selLen;
});
Cursor = Cursors.Default;
}
}