要求:
编写记事本程序
体会:
在这次作业中,让我又多了解了一些c#的知识,其中影响最深的是重构这个知识,让我觉得c#真的很简洁,他没有了其他开发软件的那种程序多而乱,让人看起来不那么反感。
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;
using System.IO;
namespace notepad
{
public partial class frmEditor : Form
{
public frmEditor()
{
InitializeComponent();
}
/// <summary>
/// 保存原始内容
/// </summary>
private string originalContent = "";
/// <summary>
/// 打开文件名
/// </summary>
private string _FileName = "";
public string FileName
{
get
{
return _FileName;
}
set
{
_FileName = value;
//在赋值时同步更新窗体标题
Text = Path.GetFileName(value) + "-我的记事本";
}
}
private void button1_Click(object sender, EventArgs e)
{
open();
}
private void open()
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileName = openFileDialog1.FileName;
try
{
originalContent = File.ReadAllText(FileName);
txtEditor.Text = originalContent;
}
catch (Exception)
{
lblInfo.Text = "无法打开文件";
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
lblTimer.Text = DateTime.Now.ToString();
}
private void frmEditor_Load(object sender, EventArgs e)
{
lblTimer.Text = "";
lblInfo.Text = "";
Text = "无标题-我的记事本";
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void btnSave_Click(object sender, EventArgs e)
{
save();
}
private void save()
{
//当内容己更改时,此标记为True,
bool ShouldSave = false;
//如果文件名不为空,表明当前是文本框中的内容是来自于文件
if (FileName != "")
{
//如果内容己更改
if (txtEditor.Text != originalContent
&& MessageBox.Show("文件己修改,保存吗?",
"保存文件",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
ShouldSave = true;
}
}
else
{
//如果用户输入了内容,并且指定了一个文件名
if (txtEditor.Text != "" && saveFileDialog1.ShowDialog() == DialogResult.OK)
{
FileName = saveFileDialog1.FileName;
ShouldSave = true;
}
}
if (ShouldSave)
{
try
{
File.WriteAllText(FileName, txtEditor.Text);
originalContent = txtEditor.Text;
lblInfo.Text = "文件己保存";
}
catch (Exception)
{
lblInfo.Text = "文件保存失败";
}
}
}
private void frmEditor_FormClosing(object sender, FormClosingEventArgs e)
{
save();
}
}
}