美文网首页
综合实验(二)C#多文本编辑器

综合实验(二)C#多文本编辑器

作者: 九除以三还是三哦 | 来源:发表于2019-12-06 16:35 被阅读0次

实验题目

设计一个多文档界面的Windows应用程序,能够实现对文档的简单处理,包括:打开、关闭、保存文件,复制、剪切、粘贴、撤销等文本处理功能,同时可以做出相关拓展。

实验方案

1、新建一个Windows窗体应用
2、分析:根据实验要求,首先需要创建一个父窗体,父窗体包含对富文本编辑的相关功能菜单,然后子窗体是富文本输入编辑框,其中还需要实现查找与替换功能,所以需要设计这三个主要的界面。

  • 父窗体设计
    Name:Form1;属性IsMdiContainer设置为“True”。


    父窗体.png
  • 子窗体设计
    窗口名称为:Form2;富文本(RichText)编辑界面名称使用默认名称(rTBDoc),属性Dock值设置为:Fill(铺满窗口),属性Modifiers值设置为:Public。


    子窗体.png
  • 查找与替换
    窗口Name:FormFind,修改属性MaximizeBox=False,MinimizeBox=False,表示没有最大化和最小化按钮,既不能最大化和最小化。FormBorderStyle=FixedDialog,窗口不能修改大小。
    属性Text="查找和替换"。
    在窗体中增加两个Label控件,属性Text分别为"查找字符串"和"替换字符串"。两个TextBox控件,属性Text=""。
    两个按钮,属性Text分别为"查找下一个"和"替换"。修改属性TopMost=true,使该窗口打开时总在其它窗体的前边。


    查找和替换.png

实现功能

基本的修改字体格式、颜色、复制、粘贴、撤销、插入图片等功能。
大部分的功能实现起来比较简单,使用函数即可,下面详细介绍几个稍微复杂一点功能的实现。

1.查找与替换功能

  • 实现的重点在于 FindRichTextBoxString(string FindString)和 ReplaceRichTextBoxString(string ReplaceString)两个函数。
  • 基本思路是将textbox中接受到的字符串在文本中寻找,因为可能不止一个位置,所以设置变量FindPostion来记录查找位置。在每次查找任务下达后,FindPostion置为零。开始查找后,FindPostion随着查找而增加。一直查找到文章末尾,FindPostion置为零。
  • 有一个小细节是找到一次之后FindPostion要加上字符串长度,使得下次查找的开始位置在此次找到字符串之后。
  • 另外一个小细节是每次找到之后要使用focus函数讲焦点转移到原来的窗口上,这样才能看到找到的标蓝位置。
  • 功能展示


    查找.png
    查找.png
    查找.png
替换.png

2.保存和另存为的功能

  • 保存文档时课本上的代码没有考虑到是新建文档还是打开已有文档,可能会造成保存多个相似文档,用户体验不太好。
  • 思路:设置一个bool变量isSaved,在文档新建、保存,等时候设置记录文档的状态,再次保存的时候,加一个if判断即可。
  • 拓展:可以再设置一个bool变量isChanged,这样在关闭的时候可以检测是否保存过给予提醒
  • 功能展示


    保存.png

3.插入图片

  • 功能比较简单,模仿新建文档即可.
  • 要把SaveFileDialog换成OpenFileDialog。
private void 插入图片_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "图片文件|*.jpg|所有文件|*.*";
            formRichText = (Form2)this.ActiveMdiChild;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Clipboard.SetDataObject(Image.FromFile(openFileDialog1.FileName), false);
                formRichText.rTBDoc.Paste();
            }
        }
  • 功能展示


    插入图片.png

代码展示

Form1

em;
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;
using System.Drawing.Text;
using System.Web;
//using System.Web.UI;

namespace SimpleMDIExample
{
    public partial class Form1 : Form
    {
        public Form2 formRichText;
        int FindPostion = 0;
        public void FindRichTextBoxString(string FindString)//查找
        {
            formRichText = (Form2)this.ActiveMdiChild;
            if (FindPostion >= formRichText.Text.Length)//已查到文本底部
            {
                MessageBox.Show("已到文本底部,再次查找将从文本开始处查找", "提示", MessageBoxButtons.OK);
                FindPostion = 0;
                return;
            }//下边语句进行查找,返回找到的位置,返回-1,表示未找到,参数1是要找的字符串
             //参数2是查找的开始位置,参数3是查找的一些选项,如大小写是否匹配,查找方向等
            FindPostion = formRichText.rTBDoc.Find(FindString,FindPostion, RichTextBoxFinds.MatchCase);
            if (FindPostion == -1)//如果未找到
            {
                MessageBox.Show("已到文本底部,再次查找将从文本开始处查找",
            "提示", MessageBoxButtons.OK);
                FindPostion = 0;//下次查找的开始位置
            }
            else//已找到
            {
                ((Form2)this.ActiveMdiChild).rTBDoc.Focus();//主窗体成为注视窗口
                //formRichText.Focus();
                FindPostion += FindString.Length;
            }//下次查找的开始位置在此次找到字符串之后
        }

        public void ReplaceRichTextBoxString(string ReplaceString)//替换
        {
            if (formRichText.rTBDoc.SelectedText.Length != 0)//如果选取了字符串
                formRichText.rTBDoc.SelectedText = ReplaceString;//替换被选的字符串
        }
            public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void MenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }
        private int _Num = 1;
        private void Form1_Load_1(object sender, EventArgs e)
        {
            tSCbBoxFontName.DropDownItems.Clear();
            InstalledFontCollection ifc = new InstalledFontCollection();
            FontFamily[] ffs = ifc.Families;
            foreach (FontFamily ff in ffs)
                tSCbBoxFontName.DropDownItems.Add(ff.GetName(1));
            LayoutMdi(MdiLayout.Cascade);
            Text = "多文本编辑器";
            WindowState = FormWindowState.Maximized;
        }

        private void 窗口层叠ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
            this.窗口层叠ToolStripMenuItem.Checked = true;
            this.垂直平铺ToolStripMenuItem.Checked = false;
            this.水平平铺ToolStripMenuItem.Checked = false;
        }

        private void 水平平铺ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
            this.窗口层叠ToolStripMenuItem.Checked = false;
            this.垂直平铺ToolStripMenuItem.Checked = false;
            this.水平平铺ToolStripMenuItem.Checked = true;
        }

        private void 垂直平铺ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
            this.窗口层叠ToolStripMenuItem.Checked = false;
            this.垂直平铺ToolStripMenuItem.Checked = true;
            this.水平平铺ToolStripMenuItem.Checked = false;
        }
        private void NewDoc()
        {
            formRichText = new Form2();
            formRichText.MdiParent = this;
            formRichText.Text = "文档" + _Num;
            formRichText.WindowState = FormWindowState.Maximized;
            formRichText.Show();
            formRichText.Activate();
            _Num++;
            formRichText.isSaved = false;
        }

        private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewDoc();
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfiledialog1 = new OpenFileDialog();
            openfiledialog1.Filter =
                "RTF格式(*.rtf)|*.rtf|文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            openfiledialog1.Multiselect = false;
            formRichText = new Form2();
            if (openfiledialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    NewDoc();
                    _Num--;
                    formRichText.isSaved = true;
                    if (openfiledialog1.FilterIndex == 1)
                        ((Form2)this.ActiveMdiChild).rTBDoc.LoadFile
                        (openfiledialog1.FileName, RichTextBoxStreamType.RichText);
                    else
                        ((Form2)this.ActiveMdiChild).rTBDoc.LoadFile
                        (openfiledialog1.FileName, RichTextBoxStreamType.PlainText);
                    ((Form2)this.ActiveMdiChild).Text = openfiledialog1.FileName;
                }
                catch
                {
                    MessageBox.Show("打开失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            openfiledialog1.Dispose();
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Save();  
                }

        private void 关闭ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(this.MdiChildren.Count()>0)
            {
                //if(!((Form2)this.ActiveMdiChild).isSaved)
                  if (MessageBox.Show("当前文件还未保存,确定要关闭当前文档吗", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                    ((Form2)this.ActiveMdiChild).Close();
                //else ((Form2)this.ActiveMdiChild).Close();
            }
            
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("确定退出应用程序吗?","提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Information)==DialogResult.OK)
            {
                foreach (Form2 fd in this.MdiChildren)
                    fd.Close();
                Application.Exit();
            }
        }

        private void TSCbBoxFontName_Click(object sender, EventArgs e)
        {
            if(this.MdiChildren.Count()>0)
            {
                RichTextBox tempRTB = new RichTextBox();
                int RtbStart = ((Form2)this.ActiveMdiChild).rTBDoc.SelectionStart;
                int len = ((Form2)this.ActiveMdiChild).rTBDoc.SelectionLength;
                int tempRtbStart = 0;
                Font font = ((Form2)this.ActiveMdiChild).rTBDoc.SelectionFont;
                if(len<=0&&null!=font)
                {
                    ((Form2)this.ActiveMdiChild).rTBDoc.Font = new Font(tSCbBoxFontName.Text, Font.Size, font.Style);
                    return;
                }
                tempRTB.Rtf = ((Form2)this.ActiveMdiChild).rTBDoc.SelectedRtf;
                for(int i=0;i<len;i++)
                {
                    tempRTB.Select(tempRtbStart + i, 1);
                    tempRTB.SelectionFont = new Font(tSCbBoxFontName.Text, tempRTB.SelectionFont.Size, tempRTB.SelectionFont.Style);
                }
                tempRTB.Select(tempRtbStart, len);
                ((Form2)this.ActiveMdiChild).rTBDoc.SelectedRtf = tempRTB.SelectedRtf;
                ((Form2)this.ActiveMdiChild).rTBDoc.Focus();
                tempRTB.Dispose();
            }
        }

        private void ChangeRTBFontStyle(RichTextBox rtb,FontStyle style)
        {
            if (style != FontStyle.Bold & style != FontStyle.Italic && style != FontStyle.Underline)
                throw new System.InvalidProgramException("字体格式错误");
            RichTextBox tempRTB = new RichTextBox();
            int curRtbStart = rtb.SelectionStart;
            int len = rtb.SelectionLength;
            int tempRtbStart = 0;
            Font font = rtb.SelectionFont;
            if(len<=0&&font!=null)
            {
                if (style == FontStyle.Bold && font.Bold || style == FontStyle.Italic && font.Italic || style == FontStyle.Underline && font.Underline)
                    rtb.Font = new Font(font, font.Style ^ style);
                else
                    if (style == FontStyle.Bold && !font.Bold || style == FontStyle.Italic && !font.Italic || style == FontStyle.Underline && !font.Underline)
                    rtb.Font = new Font(font, font.Style | style);
                return;

            }
            tempRTB.Rtf = rtb.SelectedRtf;
            tempRTB.Select(len - 1, 1);//克隆选中文字Font,用来判断
            Font tempFont = (Font)tempRTB.SelectionFont.Clone();
            for(int i=0;i<len;i++)
            {
                tempRTB.Select(tempRtbStart + i, 1);
                if (style == FontStyle.Bold && tempFont.Bold ||
                    style == FontStyle.Italic && tempFont.Italic ||
                    style == FontStyle.Underline && tempFont.Underline)
                    tempRTB.SelectionFont = new Font(tempRTB.SelectionFont, tempRTB.SelectionFont.Style ^ style);
                else
                    if (style == FontStyle.Bold && !tempFont.Bold ||
                    style == FontStyle.Italic && !tempFont.Italic ||
                    style == FontStyle.Underline && !tempFont.Underline)
                    tempRTB.SelectionFont = new Font(tempRTB.SelectionFont, tempRTB.SelectionFont.Style | style);
            }
            tempRTB.Select(tempRtbStart, len);
            rtb.Select(curRtbStart, len);
            rtb.Focus();
            tempRTB.Dispose();

        }

        private void 粗体toolStripButton_Click(object sender, EventArgs e)
        {
            formRichText = (Form2)this.ActiveMdiChild;
            //Font newFont = new Font(formRichText.rTBDoc.Font, FontStyle.Bold);
            //formRichText.rTBDoc.Font = newFont;
            if (this.MdiChildren.Count() > 0)
            ChangeRTBFontStyle(formRichText.rTBDoc, FontStyle.Bold);
        }

        private void 斜体toolStripButton_Click(object sender, EventArgs e)
        {
            if (this.MdiChildren.Count() > 0)
                ChangeRTBFontStyle(((Form2)this.ActiveMdiChild).rTBDoc, FontStyle.Italic);
        }

        private void 下画线toolStripButton_Click(object sender, EventArgs e)
        {
            if (this.MdiChildren.Count() > 0)
                ChangeRTBFontStyle(((Form2)this.ActiveMdiChild).rTBDoc, FontStyle.Underline);
        }

        private void 复制CToolStripButton_Click(object sender, EventArgs e)
        {
            Form2 formRichText = (Form2)this.ActiveMdiChild;
            formRichText.rTBDoc.Copy();
        }

        private void 剪切UToolStripButton_Click(object sender, EventArgs e)
        {
            Form2 formRichText = (Form2)this.ActiveMdiChild;
            formRichText.rTBDoc.Cut();
        }

        private void 粘贴PToolStripButton_Click(object sender, EventArgs e)
        {
            Form2 formRichText = (Form2)this.ActiveMdiChild;
            formRichText.rTBDoc.Paste();
        }

        private void 撤销toolStripButton_Click(object sender, EventArgs e)
        {
            Form2 formRichText = (Form2)this.ActiveMdiChild;
            formRichText.rTBDoc.Undo();
        }

        private void 新建NToolStripButton_Click(object sender, EventArgs e)
        {
            NewDoc();
        }

        private void 打开OToolStripButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfiledialog1 = new OpenFileDialog();
            openfiledialog1.Filter =
                "RTF格式(*.rtf)|*.rtf|文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            openfiledialog1.Multiselect = false;
            formRichText = new Form2();
            if (openfiledialog1.ShowDialog() == DialogResult.OK)
            {
                formRichText.isSaved = true;
                try
                {
                    NewDoc();
                    _Num--;
                    if (openfiledialog1.FilterIndex == 1)
                        ((Form2)this.ActiveMdiChild).rTBDoc.LoadFile
                        (openfiledialog1.FileName, RichTextBoxStreamType.RichText);
                    else
                        ((Form2)this.ActiveMdiChild).rTBDoc.LoadFile
                        (openfiledialog1.FileName, RichTextBoxStreamType.PlainText);
                    ((Form2)this.ActiveMdiChild).Text = openfiledialog1.FileName;
                }
                catch
                {
                    MessageBox.Show("打开失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            openfiledialog1.Dispose();
        }

        private void 保存SToolStripButton_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void 帮助LToolStripButton_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.Show();
        }

        private void ToolStripButton1_Click(object sender, EventArgs e)//字体颜色
        {
            formRichText = (Form2)this.ActiveMdiChild;
            ColorDialog colorDialog = new ColorDialog();
            if (colorDialog.ShowDialog() != DialogResult.Cancel)
            {
                formRichText.rTBDoc.SelectionColor = colorDialog.Color;//将当前选定的文字改变字体
            }

        }

        private void 字体_Click(object sender, EventArgs e)
        {
            formRichText = (Form2)this.ActiveMdiChild;
            FontDialog fontDialog = new FontDialog();
            if (fontDialog.ShowDialog() != DialogResult.Cancel)
            {
                formRichText.rTBDoc.SelectionFont = fontDialog.Font;//将当前选定的文字改变字体
            }
        }

        private void 搜索_Click(object sender, EventArgs e)
        {
            FindPostion = 0;
            FormFind FindReplaceDialog = new FormFind(this);//注意this
            FindReplaceDialog.Show();//打开非模式对话框使用Show()方法
        }

        private void Replace_Click(object sender, EventArgs e)
        {
            FindPostion = 0;
            FormFind FindReplaceDialog = new FormFind(this);//注意this
            FindReplaceDialog.Show();//打开非模式对话框使用Show()方法
        }
        //保存文件
        private void Save()
        {
            String str;
            formRichText = (Form2)this.ActiveMdiChild;

   

            //如果文档保存过(也就是不需要另存为)
            if (formRichText.isSaved)
            {
                
                formRichText = (Form2)this.ActiveMdiChild;       //获取当前窗口
                str = formRichText.Text.Trim();
                formRichText.rTBDoc.SaveFile(str, RichTextBoxStreamType.PlainText);
                //formRichText.isChanged = false;
                MessageBox.Show("保存成功!");
            }
            //否则,另存为
            else
            {
                SaveAs();
            }
        }

        //另存为
        private void SaveAs()
        {
            string str;
            formRichText = (Form2)this.ActiveMdiChild;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.DefaultExt = "txt";
            saveFileDialog1.Filter = "文本文件 (*.txt)|*.txt|全部文件 (*.*)|*.*";


            if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                str = saveFileDialog1.FileName;

                MessageBox.Show(str);

                if (str != "")
                {
                    formRichText.rTBDoc.SaveFile(str, RichTextBoxStreamType.PlainText);
                    formRichText.isSaved = true;
                    //formRichText.isChanged = false;
                }
                else
                {
                    MessageBox.Show("请输入文件名!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }

        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveAs();
        }

        private void 插入图片_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "图片文件|*.jpg|所有文件|*.*";
            formRichText = (Form2)this.ActiveMdiChild;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Clipboard.SetDataObject(Image.FromFile(openFileDialog1.FileName), false);
                formRichText.rTBDoc.Paste();
            }
        }
    }
    
        }

Form2

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 SimpleMDIExample
{
    public partial class Form2 : Form
    {
        //public bool isChanged = true;
        public bool isSaved;
        public Form2()
        {
            InitializeComponent();
        }
    }
}

FormFind

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 SimpleMDIExample
{
    public partial class FormFind : Form
    {
        Form1 MainForm1;

        private void FormFind_Load(object sender, EventArgs e)
        {

        }

        private void Search_Click(object sender, EventArgs e)
        {
            if (findText.Text.Length != 0)//如果查找字符串不为空,调用主窗体查找方法
                MainForm1.FindRichTextBoxString(findText.Text);//上步增加的方法
            else
                MessageBox.Show("查找字符串不能为空", "提示", MessageBoxButtons.OK);
        }

        public FormFind(Form1 form1)
        {           
            InitializeComponent();
            MainForm1 = form1;
        }

       

        private void Replace_Click(object sender, EventArgs e)
        {
            if (replaceText.Text.Length != 0)//如果查找字符串不为空,调用主窗体替换方法
                MainForm1.ReplaceRichTextBoxString( replaceText.Text);
            else//方法MainForm1.ReplaceRichTextBoxString见(26)中定义
                MessageBox.Show("替换字符串不能为空", "提示", MessageBoxButtons.OK);
        }
    }
}

实验小结

感觉综合实验作业不太有做完的时候,从基本功能的实现到一步步拓展,永远都有做得不太好的地方。代码先留在这里,希望以后可以实现更多的功能!欢迎评论区批评指正!哈哈哈


参考网站

C#做文本编辑器时如何实现文本中插入图片?
C#教程之实现文本编辑器查找替换功能
【可视化编程】实验4:C#窗体和控件综合设计(多文本编辑器)

相关文章

  • 综合实验(二)C#多文本编辑器

    实验题目 设计一个多文档界面的Windows应用程序,能够实现对文档的简单处理,包括:打开、关闭、保存文件,复制、...

  • 实验五

    实验五 使用Vim编辑器对文本进行排版 实验目的 1.初步了解Vim编辑器的原理。 2.初步掌握Vim编辑器的使用...

  • Springboot 整合editormd实现图片上传

    果函网这个项目中综合了文章模块 ,文本编辑少不了Markdown编辑器。在众多的开源编辑器中,editormd表现...

  • Vue使用Summernote富文本编辑器

    最近接手的项目中, 部分页面需要使用富文本编辑器, 对比了几款web富文本编辑器后, 综合兼容性和简洁性,最终我选...

  • Vim编辑器

    文本编辑器: 文本:纯文本,ASCII text 非丰富格式文本 文本编辑种类: 行编辑器:sed 全屏编辑器...

  • note_7.1_vim编辑器入门

    文本编辑器  文本:纯文本,ASCII text;Unicode 文本编辑种类 行编辑器:sed全屏编辑器:nan...

  • javascript富文本编辑器收集

    jquery轻量级文本编辑器Trumbowyg jQuery文本编辑器插件jWYSIWYG 其他12款文本编辑器

  • Rider 更聪明地使用C#开发Unity

    Rider 强大的跨平台C#编辑器 JetBrains Rider是一款快速强大的 C#编辑器 ,用于在Windo...

  • 前端知识 | 富文本编辑器 React-draft-wysiwy

    富文本编辑器: 富文本编辑器是一种可内嵌于浏览器的文本编辑器,富文本编辑器又不同于普通文本编辑器,程序员可到网上下...

  • VIM

    vim编辑器 vi: Visual Interface ,文本编辑器 文本:ASCII, Unicode 文本编辑...

网友评论

      本文标题:综合实验(二)C#多文本编辑器

      本文链接:https://www.haomeiwen.com/subject/uzsjgctx.html