Home Full Site
RichTextBox 컨트롤

RichTextBox 컨트롤은 TextBox와 같이 Text를 보여주는 컨트롤인데, 폰트 및 문자색 변경등 보다 풍부한 기능을 가지고 있다. RichTextBox 컨트롤은 일반 텍스트 파일뿐만 아니라 .RTF (Rich Text Format) 파일 포맷을 가진 파일을 읽어 들일 수 있다. 또한, 특정 문자를 찾거나 선택하여 폰트 크기, 색깔 등을 변경할 수 있으며, 이를 다시 .RTF로 저장하는 기능을 가지고 있다.


RichTextBox 컨트롤


RichTextBox 컨트롤 사용

다음 예제는 .RTF 파일 (혹은 Text File)을 읽어 들여 RichTextBox 컨트롤에 뿌려 주고, 모든 문자를 시스템 디폴트 폰트의 이탤릭체로 변경해 보는 예이다. RichTextBox 컨트롤에서는 폰트 및 색등을 변경하기 위해서는 먼저 특정 영역을 선택하여야 한다.

예제

public partial class Form1 : Form
{
   public Form1()
   {
      InitializeComponent();
   }

   private void btnLoadFile_Click(object sender, EventArgs e)
   {
      string filepath = txtFilename.Text;
      if (string.IsNullOrEmpty(filepath) ||
            !File.Exists(filepath))
      {
         MessageBox.Show("Invalid file name");
         return;
      }

      // Load .RTF or Text File
      richTextBox1.LoadFile(filepath);
   }

   private void btnChangeAllToItalic_Click(object sender, EventArgs e)
   {
      richTextBox1.SelectionStart = 0;
      richTextBox1.SelectionLength = richTextBox1.Text.Length;
      richTextBox1.SelectionFont = new Font(SystemFonts.DefaultFont, FontStyle.Italic);
   }
}



© csharpstudy.com