C#中关于richTextBox控件显示模式下和编辑模式下字体不一致的问题的解决方案,关闭DualFont双字体模式,改用UIFonts字体模式
发布:智码IT网 阅读:
通过代码给richTextBox控件赋值,如richTextBox1.Text = "test"后,"test"字符串的字体为"宋体",这时候如果用户手动编辑richTextBox1的内容,比如在richTextBox1控件末尾录入文本"CSharp",会发现"CSharp"的字体为"Arial",新录入的文本字体和原来的文本字体不一致,看起来特别奇怪不说,还会导致一些格式显示的问题,比如文本对齐会失效。原因是richTextBox1的LanguageOption属性默认值为:DualFont,单词dual有双重的意思,即双字体模式。
微软对于DualFont属性值解释如下:
Sets the control to dual-font mode. Used for Asian language text. The System.Windows.Forms.RichTextBox control uses an English font for ASCII text and an Asian font for Asian text.
将控件设置为双字体模式。用于亚洲语言文本。richtextbox控件对ASCII文本使用英文字体,对亚洲文本使用亚洲字体。
解决办法是手动指定richTextBox1的LanguageOption属性,设置属性值为RichTextBoxLanguageOptions.UIFonts,
微软对于UIFonts属性值解释如下:
Specifies that user-interface default fonts be used. This option is turned off by default.
指定使用用户界面默认字体。默认情况下,此选项是关闭的。
所以最终代码如下:
public Form1()
{
InitializeComponent();
//防止显示状态下的字体 和 编辑状态下新录入的字体不一致
richTextBox1.LanguageOption = RichTextBoxLanguageOptions.UIFonts;
}