📌  相关文章
📜  如何设置C#中RichTextBox中存在的内容的字体?

📅  最后修改于: 2021-05-29 14:55:40             🧑  作者: Mango

在C#中,RichTextBox控件是一个文本框,可为您提供富文本编辑控件,而高级格式设置功能还包括加载富文本格式(RTF)文件。换句话说,RichTextBox控件允许您显示或编辑流内容,包括段落,图像,表格等。在RichTextBox中,您可以设置RichTextBox控件中存在的内容的字体。您可以通过两种不同的方式设置此属性:

1.设计时:这是设置RichTextBox中存在的内容的字体的最简单方法,如以下步骤所示:

  • 第1步:创建一个Windows窗体,如下图所示:
    Visual Studio->文件->新建->项目-> WindowsFormApp
  • 步骤2:从工具箱中拖动RichTextBox控件,并将其放在Windows窗体上。您可以根据需要将RichTextBox控件放置在Windows窗体上的任何位置。
  • 步骤3:拖放之后,您将转到RichTextBox控件的属性,设置RichTextBox控件中存在的内容的字体。

    输出:

2.运行时:比上述方法有些棘手。在此方法中,可以借助给定的语法以编程方式设置RichTextBox控件中存在的内容的字体:

public virtual System.Drawing.Font Font { get; set; }

此处,字体是应用于RichTextBox内容的字体类型。以下步骤显示如何动态设置RichTextBox的Font属性:

  • 步骤1:使用RichTextBox类提供的RichTextBox()构造函数创建RichTextBox。
    // Creating RichTextBox using RichTextBox class constructor
    RichTextBox rbox = new RichTextBox();
    
  • 步骤2:创建RichTextBox之后,设置RichTextBox类提供的RichTextBox的Font属性。
    // Setting the font
    rbox.Font = new Font("Castellar", 8);
    
  • 步骤3:最后使用Add()方法将此RichTextBox控件添加到表单中。
    // Add this RichTextBox to the form
    this.Controls.Add(rbox);
    

    例子:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
      
    namespace WindowsFormsApp30 {
      
    public partial class Form1 : Form {
      
        public Form1()
        {
            InitializeComponent();
        }
      
        private void Form1_Load(object sender, EventArgs e)
        {
            // Creating and setting the 
            // properties of the label
            Label lb = new Label();
            lb.Location = new Point(251, 70);
            lb.Text = "Enter Text";
      
            // Adding this label in the form
            this.Controls.Add(lb);
      
            // Creating and setting the 
            // properties of the RichTextBox
            RichTextBox rbox = new RichTextBox();
            rbox.Location = new Point(236, 97);
            rbox.ForeColor = Color.Red;
            rbox.Font = new Font("Castellar", 8);
            rbox.Text = "!..Welcome to GeeksforGeeks..!";
      
            // Adding this RichTextBox in the form
            this.Controls.Add(rbox);
        }
    }
    }
    

    输出: