using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SimpleWrite
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool dirty = false;
private string filepath = "";
SaveFileDialog SaveFileDialog1=new SaveFileDialog();
private void MySaving()
{
if(dirty)
{
if(MessageBox.Show("需要保存文件吗?","提示框",MessageBoxButtons.YesNo)==DialogResult.Yes)
{
if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (filepath.Length == 0)
{
filepath = SaveFileDialog1.FileName;
}
StreamWriter sTmp = new StreamWriter(filepath, false, Encoding.Default);//注意编码方式,否则会出现乱码。
sTmp.Write(richTextBox1.Text);
sTmp.Flush();
sTmp.Close();
}
}
}
}
private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
{
dirty = false;
filepath = "";
}
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
MySaving();
if (OpenFileDialog1.ShowDialog() == DialogResult.OK)
{
dirty = false;
StreamReader sTmp = new StreamReader(OpenFileDialog1.FileName, Encoding.Default);//注意编码方式,否则会出现乱码。
filepath = OpenFileDialog1.FileName;
richTextBox1.Text = "";
richTextBox1.Text = sTmp.ReadToEnd();
}
}
private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
{
MySaving();
}
private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
{
MySaving();
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
MySaving();
if (dirty == false)
Close();
}
private void 自动换行ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (richTextBox1.WordWrap == true)
{
richTextBox1.WordWrap = false;
自动换行ToolStripMenuItem.Checked = false;
}
else
{
richTextBox1.WordWrap = true;
自动换行ToolStripMenuItem.Checked = true;
}
}
FontDialog FontDialog1 = new FontDialog();
private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (FontDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.Font = FontDialog1.Font;
}
}
}
}
简单记事本的实现,有BUG,在读取和写入时要注意指定编码方式,否则会出现乱码。