您的位置:首页 > 编程语言 > C#

C#之使用RichTextBox 实现简单的txt编辑器

2016-10-24 13:41 555 查看
设计要求

支持文本的简单编辑:

支持更换文字的颜色,大小和字体。

支持简单TXT文件的打开和保存。

支持文字的拷贝,粘贴和撤销等操作。

设计

一、设计FileInfo类,保存文本的颜色、大小和字体,包括每一行的信息。

二、…

实现

读取RichTextBox的每一行

private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
{
//如果文件以及
try
{
//文件路径
string path = string.Empty;
SaveFileDialog save = new SaveFileDialog();
save.Filter = "文本文件(*.txt)|*.txt"; ;
if (save.ShowDialog() == DialogResult.OK)
path = save.FileName;
if (path != string.Empty)
{
File.Delete(path);
StreamWriter sw = new StreamWriter(path, true);
for (int i = 0; i < richTextBox1.Lines.Length; i++)
{
sw.WriteLine(richTextBox1.Lines[i]);
}
sw.Flush();
sw.Close();
sw.Dispose();
}
}
catch (Exception ex)
{
throw ex;
}
}
}


从txt文件中一行行读取,赋予RichTextBox

private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
//限定扩展
fileDialog.Filter = "文本文件(*.txt)|*.txt";
fileDialog.Multiselect = true;
fileDialog.Title = "请选择文件";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string path = fileDialog.FileName;
MessageBox.Show("已选择文件:" + path, "选择文件提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
FileStream file = File.Open(path, FileMode.Open);

StreamReader filestream = new StreamReader(file);
String line = "";
int i = 0;
while ((line = filestream.ReadLine()) != null)
{
richTextBox1.Text += line + "\n";
}
file.Close();
}
}


注意
//判断文件是否存在
if (File.Exists(path))
{
DialogResult dr = MessageBox.Show("确认覆盖原文件吗?", "提示", MessageBoxButtons.OKCancel);
if (dr == DialogResult.OK)
{
//删除原文件
File.Delete(path);
}
else if (dr == DialogResult.Cancel)
{
return;
}
}


原来以为这个覆盖判断要自己去实现,但是Windows系统自己实现了。



更改RichTextBox的字体颜色和字体大小

颜色

private void 颜色ToolStripMenuItem_Click_1(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
richTextBox1.SelectionColor =       this.colorDialog1.Color;
}


字体和大小

fontDialog1.ShowDialog();
richTextBox1.Font = this.fontDialog1.Font;


接下来是我认为最难的撤销操作

将在下一篇博客中详细介绍
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编辑器