用C#寫一個記事本五

chinaherolts2008發表於2020-12-20

全套程式碼

namespace Notepad
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string filename = "";
        public Form1(string filename)
        {
            InitializeComponent();
            if (filename != null)
            {
                this.filename = filename;
                OpenFile();
            }
        }
        private void 新建NToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (txtBox.Modified == true)
            {
                DialogResult dr = MessageBox.Show("檔案發生變化,是否更改儲存?", "注意", MessageBoxButtons.YesNoCancel);
                if (dr == DialogResult.Yes)
                {
                    儲存SToolStripMenuItem_Click(sender, e);
                    return;
                }
                else if (dr == DialogResult.Cancel)
                {
                    return;
                }
                txtBox.Clear();
                this.Text = "NewNotepad";
            }
            else
            {
                txtBox.Clear();
                this.Text = "NewNotepad";
            }
        }
        private void 開啟ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                filename = openFileDialog.FileName;
                OpenFile();
            }
        }
        protected void OpenFile()
        {
            try
            {
                txtBox.Clear();
                txtBox.Text = File.ReadAllText(filename);
            }
            catch
            { MessageBox.Show("Error!"); }
        }
        private void 儲存SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                StreamWriter sw = File.AppendText(Application.ExecutablePath);
                sw.Write(txtBox.Text);
                sw.Dispose();
            }
            catch
            {
                SaveFileDialog sf = new SaveFileDialog();
                sf.DefaultExt = "*.txt";
                sf.Filter = "文字文件(.txt)|*.txt";
                if (sf.ShowDialog() == DialogResult.OK)
                {
                    StreamWriter sw = File.AppendText(sf.FileName);
                    sw.Write(txtBox.Text);
                    sw.Dispose();
                }
            }
        }
        private void 另存為ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string name;
            //SaveFileDialog類
            SaveFileDialog save = new SaveFileDialog();
            //過濾器
            save.Filter = "*.txt|*.TXT|(*.*)|*.*";
            //顯示
            if (save.ShowDialog() == DialogResult.OK)
            {
                name = save.FileName;
                FileInfo info = new FileInfo(name);
                //info.Delete();
                StreamWriter writer = info.CreateText();
                writer.Write(txtBox.Text);
                writer.Close();
            }
        }
        private void 頁面設定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //彈出頁面設定介面
            pageSetupDialog.Document = printDocument;
            pageSetupDialog.ShowDialog();
        }
        private void 列印PToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //顯示允許使用者選擇印表機的選項及其它列印選項的對話方塊
            this.printDialog.Document = this.printDocument;
            this.printDialog.PrinterSettings = this.pageSetupDialog.PrinterSettings;
            //向印表機傳送列印指令
            if (this.printDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    this.printDocument.Print();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "錯誤資訊!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void 編輯ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            剪下ToolStripMenuItem.Enabled = txtBox.Modified;
            if (txtBox.SelectedText == "")
            {
                剪下ToolStripMenuItem.Enabled = false;
                複製ToolStripMenuItem.Enabled = false;
                刪除ToolStripMenuItem.Enabled = false;
            }
            else
            {
                剪下ToolStripMenuItem.Enabled = true;
                複製ToolStripMenuItem.Enabled = true;
                刪除ToolStripMenuItem.Enabled = true;
            }
            if (txtBox.Text == "")
            {
                查詢ToolStripMenuItem.Enabled = false;
                查詢下一個ToolStripMenuItem.Enabled = false;
                查詢上一個ToolStripMenuItem.Enabled = false;
                替換ToolStripMenuItem.Enabled = false;
            }
            else
            {
                查詢ToolStripMenuItem.Enabled = true;
                查詢下一個ToolStripMenuItem.Enabled = true;
                查詢上一個ToolStripMenuItem.Enabled = true;
                替換ToolStripMenuItem.Enabled = true;
            }
            if (Clipboard.GetText() == "")
                貼上ToolStripMenuItem.Enabled = false;
            else
                貼上ToolStripMenuItem.Enabled = true;
        }
        private void 撤銷ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (txtBox.CanUndo)
            {
                txtBox.Undo();
                txtBox.ClearUndo();
            }
        }
        private void 剪下ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtBox.Cut();
        }
        private void 複製CToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtBox.Copy();
        }
        private void 貼上PToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtBox.Paste();
        }
        private void 刪除lToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtBox.SelectedText = string.Empty;
        }
        TextBox txtInput = new TextBox()
        {
            Font = new Font("宋體", 10)
        };
        TextBox txtInputReplace = new TextBox()
        {
            Font = new Font("宋體", 10)
        };
        Label lblSearch = new Label
        {
            Text = "查詢內容:",
            Size = new Size(65, 25),
            Location = new Point(5, 22)
        };
        Label lblDirection = new Label
        {
            Text = "查詢方向:",
            Size = new Size(65, 25),
            Location = new Point(5, 58)
        };
        Button FindNext = new Button
        {
            Name = "btnFindNext",
            Text = "查詢下一項",
            Size = new Size(80, 25),
            Location = new Point(265, 15)
        };
        Button Cancel = new Button
        {
            Name = "btnCancel",
            Text = "取消",
            Size = new Size(80, 25),
            Location = new Point(265, 50)
        };
        RadioButton down = new RadioButton
        {
            Name = "radDown",
            Text = "向下",
            Size = new Size(55, 25),
            Location = new Point(70, 53),
            Checked = true
        };
        RadioButton upward = new RadioButton
        {
            Name = "radUpward",
            Text = "向上",
            Size = new Size(55, 25),
            Location = new Point(140, 53),
            Checked = false
        };
        new Form FindForm = new Form
        {
            Text = "查詢文字",
            FormBorderStyle = FormBorderStyle.FixedSingle,
            MaximizeBox = false,
            MinimizeBox = false
        };
        private void 查詢ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //顯示查詢對話方塊
            txtInput.Size = new Size(190, 33);
            txtInput.Location = new Point(70, 15);
            txtInput.Multiline = true;
 
            FindNext.Click += new EventHandler(Direction_Click);
            //FindNext.Click += new EventHandler(Visible_Click);
 
            Cancel.Click += new EventHandler(Cancel_Click);
 
            FindForm.Controls.Add(lblSearch);
            FindForm.Controls.Add(lblDirection);
            FindForm.Controls.Add(txtInput);
            FindForm.Controls.Add(down);
            FindForm.Controls.Add(upward);
            FindForm.Controls.Add(FindNext);
            FindForm.Controls.Add(Cancel);
            FindForm.Top = this.Top + 50;
            FindForm.Left = this.Left + 50;
            FindForm.Height = 120;
            FindForm.Width = 380;
            FindForm.StartPosition = FormStartPosition.CenterParent;
            FindForm.ShowDialog();
        }
        private void Visible_Click(object sender, EventArgs e)
        {
            FindForm.Visible = false;
        }
        private void Cancel_Click(object sender, EventArgs e)
        {
            //關閉對話方塊
            FindForm.Close();
            ReplaceForm.Close();
        }
        private void Direction_Click(object sender, EventArgs e)
        {
            //選擇字元查詢方向
            if (down.Checked == true)
            {
                Find_Click(sender, e);
            }
            else if (upward.Checked == true)
            {
                FindLast_Click(sender, e);
            }
        }
        int nextPosition, firstPosition;
        string word;
        Boolean IF = false;
        private void Find_Click(object sender, EventArgs e)
        {
            txtBox.Focus();
            FindWords(txtInput.Text);
        }
        private void FindWords(string words)
        {
            //向下查詢字元
            if (nextPosition >= txtBox.Text.Length)
                nextPosition = 0;
            firstPosition = txtBox.Text.IndexOf(words, nextPosition);
            if (firstPosition == -1)
                nextPosition = 0;
            else
            {
                txtBox.Select(firstPosition, words.Length);
                nextPosition = firstPosition + 1;
            }
            word = words;
            IF = true;
        }
        private void 查詢下一個ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //查詢下一項,如果未查詢過,則顯示查詢對話方塊
            down.Checked = true;
            upward.Checked = false;
            try
            {
                FindWords(word);
            }
            catch
            {
                查詢ToolStripMenuItem_Click(sender, e);
            }
        }
        private void FindLast_Click(object sender, EventArgs e)
        {
            txtBox.Focus();
            FindWordsLast(txtInput.Text);
        }
        private void FindWordsLast(string words)
        {
            //向上查詢字元
            if (IF == false)
                nextPosition = txtBox.Text.Length;
            if (nextPosition < 0)
                nextPosition = txtBox.Text.Length;
 
            firstPosition = txtBox.Text.LastIndexOf(words, nextPosition);
 
            if (firstPosition == -1)
                nextPosition = txtBox.Text.Length;
            else
            {
                txtBox.Select(firstPosition, words.Length);
                nextPosition = firstPosition - 1;
            }
            word = words;
            IF = true;
        }
        private void 查詢上一個ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //查詢上一項,如果未查詢過,則顯示查詢對話方塊
            upward.Checked = true;
            down.Checked = false;
            try
            {
                FindWordsLast(word);
            }
            catch
            {
                查詢ToolStripMenuItem_Click(sender, e);
            }
        }
        Label LblReplace = new Label
        {
            Name = "lblReplace",
            Text = "替換:",
            Size = new Size(55, 25),
            Location = new Point(15, 50)
        };
        Form ReplaceForm = new Form
        {
            Text = "替換文字",
            FormBorderStyle = FormBorderStyle.FixedSingle,
            MaximizeBox = false,
            MinimizeBox = false
        };
        private void 替換ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtInput.Size = new Size(190, 30);
            txtInput.Location = new Point(70, 12);
            txtInput.Multiline = true;
 
            txtInputReplace.Size = new Size(190, 30);
            txtInputReplace.Location = new Point(70, 47);
            txtInputReplace.Multiline = true;
 
            Button Replace = new Button
            {
                Name = "btnReplace",
                Text = "替換",
                Size = new Size(80, 25),
                Location = new Point(265, 15)
            };
            Replace.Click += new EventHandler(Replace_Click);
            Cancel.Click += new EventHandler(Cancel_Click);
 
            ReplaceForm.Controls.Add(lblSearch);
            ReplaceForm.Controls.Add(LblReplace);
            ReplaceForm.Controls.Add(txtInput);
            ReplaceForm.Controls.Add(txtInputReplace);
            ReplaceForm.Controls.Add(Replace);
            ReplaceForm.Controls.Add(Cancel);
            ReplaceForm.Top = this.Top + 50;
            ReplaceForm.Left = this.Left + 50;
            ReplaceForm.Height = 140;
            ReplaceForm.Width = 380;
            ReplaceForm.StartPosition = FormStartPosition.CenterParent;
            ReplaceForm.ShowDialog();
        }
        private void Replace_Click(object sender, EventArgs e)
        {
            txtBox.Text = txtBox.Text.Replace(txtInput.Text, txtInputReplace.Text);
        }
        private void 全選AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtBox.SelectAll();
        }
        private void 自動換行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //預設自動換行,點選按鈕開啟或關閉自動換行
            if (自動換行ToolStripMenuItem.Checked == true)
            {
                txtBox.WordWrap = false;
                自動換行ToolStripMenuItem.Checked = false;
            }
            else
            {
                txtBox.WordWrap = true;
                自動換行ToolStripMenuItem.Checked = true;
            }
        }
        private void 字型ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //提示使用者從本地計算機安裝的字型中選擇字型字號
            FontDialog fontDialog = new FontDialog();
            if (fontDialog.ShowDialog() == DialogResult.OK)
            {
                txtBox.Font = fontDialog.Font;
            }
        }
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            //窗體的txtBox控制元件隨窗體改變而改變的大小
            if (狀態列ToolStripMenuItem.Checked == true && 工具欄TToolStripMenuItem.Checked == true)
                txtBox.Height = this.Height - menuStrip.Height - toolStrip.Height - statusStrip.Height - 39;
            else if (狀態列ToolStripMenuItem.Checked == false && 工具欄TToolStripMenuItem.Checked == true)
                txtBox.Height = this.Height - menuStrip.Height - toolStrip.Height - 39;
            else if (狀態列ToolStripMenuItem.Checked == true && 工具欄TToolStripMenuItem.Checked == false)
                txtBox.Height = this.Height - menuStrip.Height - statusStrip.Height - 39;
            else
                txtBox.Height = this.Height - menuStrip.Height - 39;
            txtBox.Width = this.Width - 16;
        }
        private void 工具欄TToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //預設開啟工具欄,點選按鈕開啟或關閉工具欄
            if (工具欄TToolStripMenuItem.Checked == true)
            {
                toolStrip.Visible = false;
                工具欄TToolStripMenuItem.Checked = false;
                txtBox.Top = 25;
            }
            else if (工具欄TToolStripMenuItem.Checked == false)
            {
                toolStrip.Visible = true;
                工具欄TToolStripMenuItem.Checked = true;
                txtBox.Top = 50;
            }
            Form1_SizeChanged(sender, e);
        }
        private void 放大ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //放大字型大小
            var fontsize = txtBox.Font.Size;
            var fontFamily = txtBox.Font.FontFamily;
            txtBox.Font = new Font(fontFamily, fontsize + 1);
        }
        private void 縮小ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //縮小字型大小
            var fontsize = txtBox.Font.Size;
            var fontFamily = txtBox.Font.FontFamily;
            txtBox.Font = new Font(fontFamily, fontsize - 1);
        }
        private void 恢復預設縮放ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //恢復預設字型大小
            txtBox.Font = new Font(txtBox.Font.FontFamily, 11);
        }
        private void 狀態列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //預設顯示狀態列,點選按鈕顯示或關閉狀態列
            if (狀態列ToolStripMenuItem.Checked == true)
            {
                statusStrip.Visible = false;
                狀態列ToolStripMenuItem.Checked = false;
            }
            else if (狀態列ToolStripMenuItem.Checked == false)
            {
                statusStrip.Visible = true;
                狀態列ToolStripMenuItem.Checked = true;
            }
            Form1_SizeChanged(sender, e);
        }
        //private int GetStringLen(string s)
        //{
        //    if (!string.IsNullOrEmpty(s))
        //    {
        //        int len = s.Length;
        //        for (int i = 0; i < s.Length; i++)
        //        {
        //            if (s[i] > 255)
        //                len++;
        //        }
        //        return len;
        //    }
        //    return 0;
        //}
        private void 檢視幫助HToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //呼叫系統自帶的瀏覽器開啟網頁檢視幫助
            Process.Start("https://jingyan.baidu.com/article/a24b33cdd86a0f19fe002be9.html");
        }
        private void 關於記事本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //關於記事本說明
            Label lblTitle = new Label()
            {
                Text = "多功能記事本",
                Size = new Size(150, 25),
                Location = new Point(100, 50)
            };
            Label lblEdition = new Label()
            {
                Text = "版本號:個性測試版",
                Size = new Size(150, 25),
                Location = new Point(85, 100)
            };
            Label lblMail = new Label()
            {
                Text = "E-Mail:",
                Size = new Size(55, 25),
                Location = new Point(30, 180)
            };
            LinkLabel llblMail = new LinkLabel()
            {
                Text = "2417525822@qq.com",
                Size = new Size(110, 25),
                Location = new Point(85, 180)
            };
            Label lblCNDS = new Label()
            {
                Text = "CNDS部落格:",
                Size = new Size(65, 25),
                Location = new Point(20, 220)
            };
            LinkLabel llblCNDS = new LinkLabel()
            {
                Text = "https://blog.csdn.net/UFO_Harold",
                Size = new Size(200, 25),
                Location = new Point(85, 220)
            };
            Form about = new Form
            {
                Text = "關於記事本",
                FormBorderStyle = FormBorderStyle.FixedSingle,
                MaximizeBox = false
            };
 
            llblCNDS.Click += new EventHandler(LlblCNDS_Click);
            about.Controls.Add(lblTitle);
            about.Controls.Add(lblEdition);
            about.Controls.Add(lblMail);
            about.Controls.Add(llblMail);
            about.Controls.Add(lblCNDS);
            about.Controls.Add(llblCNDS);
            about.Top = this.Top + this.Height / 2 - about.Height / 2;
            about.Left = this.Left + this.Width / 2 - about.Width / 2;
            about.StartPosition = FormStartPosition.CenterParent;
            about.ShowDialog();
        }
        private void LlblCNDS_Click(object sender, EventArgs e)
        {
            Process.Start("https://blog.csdn.net/UFO_Harold");
        }
        private void 新建toolStripButton_Click(object sender, EventArgs e)
        {
            新建NToolStripMenuItem_Click(this, e);
        }
        private void 另存為toolStripButton_Click(object sender, EventArgs e)
        {
            另存為ToolStripMenuItem_Click(this, e);
        }
        private void 儲存StoolStripButton_Click(object sender, EventArgs e)
        {
            儲存SToolStripMenuItem_Click(this, e);
        }
        private void 列印PtoolStripButton_Click(object sender, EventArgs e)
        {
            列印PToolStripMenuItem_Click(this, e);
        }
        private void 剪下toolStripButton_Click(object sender, EventArgs e)
        {
            剪下ToolStripMenuItem_Click(this, e);
        }
        private void 複製CtoolStripButton_Click(object sender, EventArgs e)
        {
            複製CToolStripMenuItem_Click(this, e);
        }
        private void 貼上PtoolStripButton_Click(object sender, EventArgs e)
        {
            貼上PToolStripMenuItem_Click(this, e);
        }
        private void 幫助HtoolStripButton_Click(object sender, EventArgs e)
        {
            檢視幫助HToolStripMenuItem_Click(this, e);
        }
        private void Timer_Tick(object sender, EventArgs e)
        {
            //顯示編輯游標所在幾行幾列
            int row = txtBox.GetLineFromCharIndex(txtBox.SelectionStart) + 1;
            int col = (txtBox.SelectionStart - txtBox.GetFirstCharIndexFromLine(txtBox.GetLineFromCharIndex(txtBox.SelectionStart))) + 1;
            toolStripStatusLblLocation.Text = "第 " + row + " 行, 第 " + col + " 列";
            toolStripStatusLblNow.Text = "" + DateTime.Now.ToLocalTime();
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //關閉窗體時如果已修改內容,則彈出是否儲存對話方塊,否則直接關閉窗體
            if (txtBox.Modified == true)
            {
                DialogResult dr = MessageBox.Show("檔案發生變化,是否更改儲存?", "注意", MessageBoxButtons.YesNoCancel);
                if (dr == DialogResult.Yes)
                {
                    儲存SToolStripMenuItem_Click(sender, e);
                    return;
                }
                else if (dr == DialogResult.No)
                {
                    return;
                }
                else if (dr == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
        }
    }
}

win10環境下執行程式的結果
在這裡插入圖片描述

注:
控制元件請自行改名,也可使用預設
控制元件名,此次程式的控制元件均已自定義名稱,然後再雙擊控制元件便會自動建立控制元件的事件函式並跳到內碼表,全數copy程式碼到自己新建的程式可能執行不起來,因為控制元件的事件需要雙擊控制元件才跳轉到事件函式,事件方法前出現引用不是為 0 即生效;
查詢上一項下一項功能混用時會有一些bug,達不到預期效果,但能執行,不會報錯,一點邏輯上的問題,目前沒有想到解決方法,大家可自行深入摸索,如有可以改進的地方可聯絡博主;
整個專案原始碼的檔案:(原始碼僅供學習交流使用,如需使用請安裝.NET Framework 4.7.2框架,且圖示可能因檔案路徑不同而無法顯示,修改檔案路徑即可)
藍奏雲:https://www.lanzous.com/i9r643e
百度網盤:https://pan.baidu.com/s/1BagLHS9bOG2jvaOcHgeUgA 提取碼:y639
Github:https://github.com/Harold-666/Notepad/tree/master
該文是從CSND搬家過來的文章,已修正,覺得CSND不好用,搬至部落格園在此安家,總的來說,在部落格園的體驗感比在CSDN好很多,往後請各位博友多多指教!我的部落格園地址:https://www.cnblogs.com/Harold-popo

狀態列圖示設定
在這裡插入圖片描述

專案檔案目錄
在這裡插入圖片描述

相關文章