專案資訊
- 版本:1.0
- 編輯模組:全選、插入日期時間(自動換行待完成)
- 完整原始碼請聯繫作者:henanlinzhoulcl@163.com
核心功能程式碼節錄
基本架構
namespace MyNotePad {
public partial class MyNotePad : Form {
public MyNotePad() {
InitializeComponent();
this.toolStripStatusLabel3.Text = DateTime.Now.DayOfWeek.ToString();
}
// ...
}
}
檔案操作:新建、開啟、儲存、另存新檔
// 新建
private void 新建ToolStripMenuItem_Click(...) {
if (this.textBox1.Text != "") {
DialogResult d = MessageBox.Show("檔案文字已變更,想儲存嗎?", "MyNotePad",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
switch (d) {
case DialogResult.Yes: 儲存邏輯(); break;
case DialogResult.No: this.textBox1.Text = ""; break;
case DialogResult.Cancel: break;
}
}
}
// 開啟
private void 開啟ToolStripMenuItem_Click(...) {
// 同樣檢查是否儲存 → OpenFileDialog → StreamReader 讀取
}
// 儲存 / 另存新檔
private void 儲存ToolStripMenuItem_Click(...) {
using (SaveFileDialog saveDig = new SaveFileDialog()) {
saveDig.Filter = "文字文件(*.txt)|*.txt";
if (saveDig.ShowDialog() == DialogResult.OK) {
StreamWriter sw = new StreamWriter(saveDig.FileName, false, Encoding.Default);
sw.Write(this.textBox1.Text);
sw.Close();
this.Text = saveDig.FileName;
}
}
}
編輯功能
// 全選
private void 全選ToolStripMenuItem_Click(...) { this.textBox1.SelectAll(); }
// 插入日期時間
private void 日期ToolStripMenuItem_Click(...) {
if (this.textBox1.SelectedText != "")
this.textBox1.SelectedText = DateTime.Now.ToString();
else
this.textBox1.Text += DateTime.Now;
}
// 字體設定
private void 字體ToolStripMenuItem_Click(...) {
if (fontDialog1.ShowDialog() == DialogResult.OK)
textBox1.Font = fontDialog1.Font;
}
視窗狀態管理
// 視窗大小調整同步 TextBox
private void MyNotePad_Resize(...) {
this.panel1.Width = this.Size.Width - 25;
this.panel1.Height = this.Size.Height - 50;
this.textBox1.Width = this.panel1.Width;
this.textBox1.Height = this.panel1.Height;
}
// 狀態列顯示/隱藏
private void 狀態列ToolStripMenuItem_Click(...) {
if (this.statusStrip1.Visible == false) this.statusStrip1.Visible = true;
else { this.statusStrip1.Visible = false; this.textBox1.Height += 10; }
}
// 計時器更新時間
private void timer1_Tick(...) {
this.toolStripStatusLabel1.Text = "現在時間是:" + DateTime.Now.ToString();
}
關閉視窗確認
private void MyNotePad_FormClosing(...) {
// 同新建/開啟的儲存確認邏輯
}
技術重點
- 使用
StreamReader/StreamWriter 處理文字檔,指定 Encoding.Default
- 多重文件狀態追蹤(
Text 屬性存檔案路徑)
- 統一的「未儲存變更」確認邏輯封裝
- ToolStrip/StatusStrip 現代化 UI 控制項