實驗題目
設計一個多文檔界面的Windows應用程序牺堰,能夠實現對文檔的簡單處理拄轻,包括:打開、關閉伟葫、保存文件恨搓,復制、剪切筏养、粘貼斧抱、撤銷等文本處理功能,同時可以做出相關拓展渐溶。
實驗方案
1辉浦、新建一個Windows窗體應用
2、分析:根據實驗要求茎辐,首先需要創(chuàng)建一個父窗體宪郊,父窗體包含對富文本編輯的相關功能菜單掂恕,然后子窗體是富文本輸入編輯框,其中還需要實現查找與替換功能弛槐,所以需要設計這三個主要的界面懊亡。
-
父窗體設計
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置為零。
- 有一個小細節(jié)是找到一次之后FindPostion要加上字符串長度盏道,使得下次查找的開始位置在此次找到字符串之后稍浆。
- 另外一個小細節(jié)是每次找到之后要使用focus函數講焦點轉移到原來的窗口上,這樣才能看到找到的標藍位置猜嘱。
-
功能展示
查找.png
查找.png
查找.png
2.保存和另存為的功能
- 保存文檔時課本上的代碼沒有考慮到是新建文檔還是打開已有文檔衅枫,可能會造成保存多個相似文檔,用戶體驗不太好朗伶。
- 思路:設置一個bool變量isSaved弦撩,在文檔新建、保存论皆,等時候設置記錄文檔的狀態(tài)益楼,再次保存的時候,加一個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);
}
}
}
實驗小結
感覺綜合實驗作業(yè)不太有做完的時候乙墙,從基本功能的實現到一步步拓展颖变,永遠都有做得不太好的地方生均。代碼先留在這里,希望以后可以實現更多的功能腥刹!歡迎評論區(qū)批評指正马胧!哈哈哈
參考網站
C#做文本編輯器時如何實現文本中插入圖片?
C#教程之實現文本編輯器查找替換功能
【可視化編程】實驗4:C#窗體和控件綜合設計(多文本編輯器)