陳鍾誠

Version 1.0

C# 視窗程式:設計文字編輯器

教學錄影:

專案下載:

執行結果

文字編輯器執行畫面

程式碼

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
    public partial class FormEditor : Form
    {
        String filePath = null;

        public FormEditor()
        {
            InitializeComponent();
        }

        public static String fileToText(String filePath)
        {
            StreamReader file = new StreamReader(filePath);
            String text = file.ReadToEnd();
            file.Close();
            return text;
        }

        public static void textToFile(String filePath, String text)
        {
            StreamWriter file = new StreamWriter(filePath);
            file.Write(text);
            file.Close();
        }

        private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                String text = fileToText(openFileDialog.FileName);
                richTextBox.Text = text;
                filePath = openFileDialog.FileName;
            }
        }

        private void newFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox.Text = "";
            filePath = null;
        }

        private void saveFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (filePath == null)
            {
                dialogSaveFile();
            }
            else
            {
                textToFile(filePath, richTextBox.Text);
            }
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dialogSaveFile();
        }

        public void dialogSaveFile()
        {
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                textToFile(saveFileDialog.FileName, richTextBox.Text);
                filePath = saveFileDialog.FileName;
            }
        }

    }
}