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;
namespace Notepad
{
public partial class frmNotepad : Form
{
//****************************************
/*布尔变量b用于判断文件是新建的还是从磁盘打开的 true 表示从磁盘打开,false表示文件是新建的,默认值为false*/
bool b = false;
/*布尔变量s用于判断文件是否被保存 true 表示已经被保存,false表示未被保存,默认值为true*/
bool s = true;
//***********************************
public frmNotepad()
{
InitializeComponent();
richTextBox1.Text = "";
}
//***********************************************
// 多格式文本框的TextChanged事件代码
//************************************************
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
//文本框被修改后,设置s为false,表示文件未保存
s = false;
}
//*****************************************
// 【文件】菜单各菜单项的单击代码
//*******************************************
//*****************************************
// 【新建】菜单代码
//*********************************************
private void 新建NToolStripMenuItem_Click(object sender, EventArgs e)
{
//判断当前文件是否是从磁盘打开,或者新建时文档不为空,并且文件未被保存
if(b == true || richTextBox1.Text.Trim() != "")
{
//若文件未保存
if(s == false)
{
string result;
result = MessageBox.Show("文件尚未保存,是否保存?", "保存文件", MessageBoxButtons.YesNoCancel).ToString();
switch(result)
{
case"Yes":
//若文件是从磁盘打开的
if(b == true)
{
//按文件打开的路径保存文件
richTextBox1.SaveFile(sdlgNotepad.FileName);
}else if(sdlgNotepad.ShowDialog()==DialogResult.OK)
{
richTextBox1.SaveFile(sdlgNotepad.FileName);
}
s = true;