RichTextBox

来源:互联网 发布:权力的游戏 夜王 知乎 编辑:程序博客网 时间:2024/05/21 09:58
1.
//自动换行
            //this.richTextBox1.WordWrap = true;

            //向RichTextBox1中追加内容
            //this.richTextBox1.AppendText(value);

            //滚动到控件光标处 
            //this.richTextBox1.ScrollToCaret();
2.加载选择的文件
private void btnRead_Click(object sender, EventArgs e)
        {
            string filepath = this.txtFilePath.Text.ToString();

            if (filepath.Length == 0)
            {
                MessageBox.Show("请选择文件!");
                return;
            }

            //清空RichTextBox控件中的内容
            this.richTextBox1.Text = "";
            this.richTextBox1.Controls.Clear();

            //获取文件扩展名
            string filetype = filepath.Substring(filepath.LastIndexOf(".") + 1).ToLower();

            switch (filetype)
            {
                case "txt":
                    this.richTextBox1.LoadFile(filepath, RichTextBoxStreamType.PlainText);
                    break;
                case "rtf":
                    this.richTextBox1.LoadFile(filepath, RichTextBoxStreamType.RichText);
                    break;
                case "xml":
                    this.richTextBox1.LoadFile(filepath, RichTextBoxStreamType.RichText);
                    break;
                case "jpg":
                    this.LoadPicture(filepath);
                    break;
                case "png":
                    this.LoadPicture(filepath);
                    break;

                default:
                    break;
            }

        }

3.加载图片的方法
private void LoadPicture(string filename)
        {
            Image img = Image.FromFile(filename);

            PictureBox pic = new PictureBox();
            pic.Width = 300;
            pic.Height = 200;
            pic.Image = img;
            pic.SizeMode = PictureBoxSizeMode.StretchImage;

            this.richTextBox1.Controls.Add(pic);      
        }
4,保存richtextbox的内容

private void btnSave_Click(object sender, EventArgs e)
        {
            saveFileDialog1.RestoreDirectory = false;
            saveFileDialog1.FileName = "export.rtf";
            string filepath = "";

            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                filepath = this.saveFileDialog1.FileName;
            }

            this.richTextBox1.SaveFile(filepath);

//如果保存的是txt格式
//this.richTextBox1.SaveFile(filepath,RichTextBoxStreamType.PlainText);

            MessageBox.Show("保存成功!");         
        }
0 0