c# - 使用 RichTextBox.SelectionFont 时出现 nullReferenceException

标签 c# .net fonts richtextbox

when the selection area is combined with 2 areas that has different fonts, it returns null.代码如下:

private Font myGetSelectionFont()
{
    Font t = this.workspace.SelectionFont;
    if (t == null)
        return defaultFont;
    else return t;
}
private void toolStripComboBox_size_SelectedIndexChanged(object sender, EventArgs e)
{
    string sizeString = ((ToolStripComboBox)sender).SelectedItem.ToString();
    float curSize = float.Parse(sizeString);
    Font oldFont = myGetSelectionFont();
    Font newFont = this.getFont(oldFont.FontFamily.Name, curSize, oldFont.Style);
    this.setFontIcons(newFont);
    this.workspace.SelectionFont = newFont;
    this.workspace.Focus();
}

为所选区域设置不同的字体没有问题,但我不知道所选区域的字体大小和其他属性。我该怎么办?

我想我可以选择将字体设置为选中区域之前的字体,或者选中区域之后的字体,但我不知道该怎么做。

最佳答案

一个可能的解决方案是循环

private void toolStripComboBox_size_SelectedIndexChanged(object sender, EventArgs e)
{
    float size = float.Parse(((ToolStripComboBox)sender).SelectedItem.ToString());
    SetFontSize(richTextBox1, size);
}

private void SetFontSize(RichTextBox rtb, float size)
{
    int selectionStart = rtb.SelectionStart;
    int selectionLength = rtb.SelectionLength;
    int selectionEnd = selectionStart + selectionLength;
    for (int x = selectionStart; x < selectionEnd; ++x)
    {
        // Set temporary selection
        rtb.Select(x, 1);
        // Toggle font style of the selection   
        rtb.SelectionFont = new Font(rtb.SelectionFont.FontFamily, size, rtb.SelectionFont.Style);
    }
    // Restore the original selection
    rtb.Select(selectionStart, selectionLength);
}

关于c# - 使用 RichTextBox.SelectionFont 时出现 nullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21089167/

相关文章:

c# - 分层 TreeView 实现

C# 将 FontDialog 设置为仅显示 TrueType 字体

java - 无法在 PDBox PDF 文档中插入制表符和空格

.net - 将 JSON 对象反序列化到 .NET 列表中

windows - 如何让 GNU Unifont 或 Free Mono 在 gvim windows 上工作?

C# WPF 代码在 Visual Studio 中的运行速度比在控制台中的运行速度快,而在另一个文件夹中的运行速度较慢

c# - 使用多行和组的正则表达式

c# - 继承泛型类时的多态性

c# - 在 C# 中列出目录时如何过滤文件

c# - 添加 WCF 服务引用时,HTTP 请求被客户端身份验证方案 'Anonymous' 错误禁止