c#第二次作業
要求:
編寫記事本程式
體會:
在這次作業中,讓我又多瞭解了一些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();
}
}
}