记事本应该用 TextBox ,TextBox 不带有字体、字号等样式。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Diagnostics;
namespace Hongcing.Notepad
{
/// <summary>
/// 主窗口
/// </summary>
public partial class MainForm : Form
{
/// <summary>
/// 文件路径
/// </summary>
string filePath;
/// <summary>
/// 文件标题
/// </summary>
string fileTitle;
/// <summary>
/// 文件属性
/// </summary>
string fileAttrib;
/// <summary>
/// 消息框标题
/// </summary>
string caption;
/// <summary>
/// 文件编码
/// </summary>
Encoding fileEncoding = Encoding.Default;
/// <summary>
/// 关于对话框
/// </summary>
AboutBox aboutBox = new AboutBox();
/// <summary>
/// 新建主窗口实例
/// </summary>
public MainForm()
{
InitializeComponent();
}
/// <summary>
/// 获取文件编码
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="curEncoding">当前编码</param>
/// <returns>文件的编码</returns>
private Encoding GetFileEncoding(string filePath, Encoding curEncoding)
{
Encoding retEncoding = curEncoding;
FileStream input = null;
BinaryReader binReader = null;
try
{
input = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
binReader = new BinaryReader(input);
//读取字节数
int length = 4;
if (input.Length < length)
length = (int)input.Length;
byte[] bom = binReader.ReadBytes(length);
if (bom.Length >= 3 && bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF)
return retEncoding = Encoding.UTF8;
if (bom.Length >= 2 && bom[0] == 0xFF && bom[1] == 0xFE)
//再检测是否为UTF32
retEncoding = Encoding.Unicode;
if (bom.Length >= 2 && bom[0] == 0xFE && bom[1] == 0xFF)
return retEncoding = Encoding.BigEndianUnicode;
if (bom.Length >= 4 && bom[0] == 0xFF && bom[1] == 0xFE && bom[2] == 0x00 && bom[3] == 0x00)
return retEncoding = Encoding.UTF32;
if (bom.Length >= 4 && bom[0] == 0x00 && bom[1] == 0x00 && bom[2] == 0xFE && bom[3] == 0xFF)
return retEncoding = Encoding.GetEncoding(12001);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (binReader != null)
binReader.Close();
if (input != null)
input.Close();
}
return retEncoding;
}
/// <summary>
/// 新建文件
/// </summary>
private void NewFile()
{
textBoxMain.Clear();
filePath = "";
fileEncoding = Encoding.Default;
}
/// <summary>
/// 打开文件
/// </summary>
private void OpenFile()
{
openDlg.FileName = "";
openDlg.InitialDirectory = Environment.CurrentDirectory;
if (openDlg.ShowDialog() == DialogResult.OK)
{
try
{
textBoxMain.Clear();
filePath = openDlg.FileName;
fileEncoding = GetFileEncoding(filePath, fileEncoding);
textBoxMain.Text = File.ReadAllText(filePath, fileEncoding);
//string allText = File.ReadAllText(filePath, fileEncoding);
//textBoxMain.Clear();
//filePath = openDlg.FileName;
//fileEncoding = GetFileEncoding(filePath, fileEncoding);
//textBoxMain.Text = allText;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
/// <summary>
/// 另存为文件
/// </summary>
private void SaveAsFile()
{
saveDlg.FileName = filePath;
saveDlg.InitialDirectory = Environment.CurrentDirectory;
if (saveDlg.ShowDialog() == DialogResult.OK)
{
string fileNameTemp = saveDlg.FileName;
if (File.Exists(fileNameTemp) && new FileInfo(filePath).IsReadOnly)//可能引发异常
{
string showInfo = fileNameTemp + "\r\n该文件已存在,而且具有只读属性。\r\n请使用其他文件名。";
MessageBox.Show(showInfo, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
SaveAsFile();
}
else
{
try
{
File.WriteAllText(fileNameTemp, textBoxMain.Text, fileEncoding);
textBoxMain.Modified = false;
filePath = saveDlg.FileName;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
/// <summary>
/// 保存文件
/// </summary>
private void SaveFile()
{
if (filePath.Length != 0)
{
if (File.Exists(filePath) && new FileInfo(filePath).IsReadOnly)//可能引发异常
{
string showInfo = filePath + "\r\n该文件已存在,而且具有只读属性。\r\n请使用其他文件名。";
MessageBox.Show(showInfo, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
SaveAsFile();
}
else
{
try
{
File.WriteAllText(filePath, textBoxMain.Text, fileEncoding);
textBoxMain.Modified = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
else
SaveAsFile();
}
/// <summary>
/// 自动改变菜单、按钮启用状态。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timerMain_Tick(object sender, EventArgs e)//是否可以改为在鼠标或者键盘响应时启动,不响应时关闭?
{
if (string.IsNullOrEmpty(filePath))
{
filePath = "";
fileTitle = "无标题";
fileAttrib = "\u0020";
}
else
{
fileTitle = Path.GetFileName(filePath);
if (File.Exists(filePath) && new FileInfo(filePath).IsReadOnly)
fileAttrib = "(只读)";
else
fileAttrib = "\u0020";
}
this.Text = fileTitle + fileAttrib + "- 记事本";
if (textBoxMain.CanUndo)
menuUndo.Enabled = true;
else
menuUndo.Enabled = false;
if (textBoxMain.SelectedText.Length == 0)
{
menuCut.Enabled = false;
menuCopy.Enabled = false;
menuDelete.Enabled = false;
}
else
{
menuCut.Enabled = true;
menuCopy.Enabled = true;
menuDelete.Enabled = true;
}
if (Clipboard.ContainsText())
menuPaste.Enabled = true;
else
menuPaste.Enabled = false;
if (textBoxMain.Text.Length == 0)
menuSelectAll.Enabled = false;
else
menuSelectAll.Enabled = true;
if (textBoxMain.Modified)
labelTextModified.Text = "文字已经改变。";
else
labelTextModified.Text = "文字没有改变。";
labelTextEncoding.Text = "当然文本编码:" + fileEncoding.EncodingName;
labelNull.Text = "Ln " + (textBoxMain.Lines.Length + 1) + ", Col " + (textBoxMain.SelectionStart + 1);
}
/// <summary>
/// 载入窗体
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainForm_Load(object sender, EventArgs e)
{
caption = aboutBox.AssemblyTitle;
timerMain.Start();
statusStripMain.Visible = false;
labelTextModified.Visible = labelTextEncoding.Visible = false;
string[] args = Program.args;
string cmdLine = "";
foreach (string arg in args)
cmdLine += arg;
string filePathTemp = cmdLine.Replace("/p", "").Replace("\"", "").Trim();
if (filePathTemp.Length == 0)
Environment.CurrentDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
else
{
if (File.Exists(filePathTemp) == false && Path.HasExtension(filePathTemp) == false)
filePathTemp = filePathTemp + ".txt";
if (File.Exists(filePathTemp))
{
try
{
string allText = File.ReadAllText(filePathTemp, fileEncoding);
textBoxMain.Clear();
filePath = filePathTemp;
fileEncoding = GetFileEncoding(filePath, fileEncoding);
textBoxMain.Text = allText;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
textBoxMain.SelectionStart = 0;
}
else
{
string showInfo = string.Format("找不到文件: {0}。\r\n\r\n要创建新文件吗?", filePathTemp);
switch (MessageBox.Show(showInfo, caption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning))
{
case DialogResult.Yes:
try
{
File.WriteAllText(filePathTemp, textBoxMain.Text, fileEncoding);
textBoxMain.Modified = false;
textBoxMain.Clear();
string allText = File.ReadAllText(filePathTemp, fileEncoding);
textBoxMain.Clear();
filePath = filePathTemp;
fileEncoding = GetFileEncoding(filePath, fileEncoding);
textBoxMain.Text = allText;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
break;
case DialogResult.Cancel:
this.Dispose(true);
Application.Exit();
break;
}
}
}
}
/// <summary>
/// 关闭窗体
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainForm_Closing(object sender, FormClosingEventArgs e)
{
if (textBoxMain.Modified)
{
if (filePath.Length != 0 || textBoxMain.Text.Length != 0)
{
string showInfo = "文件 {0} 的文字已经改变。\r\n\r\n想保存文件吗?";
if (filePath.Length == 0)
showInfo = string.Format(showInfo, fileTitle);
else
showInfo = string.Format(showInfo, filePath);
switch (MessageBox.Show(showInfo, caption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning))
{
case DialogResult.Yes:
SaveFile();
if (textBoxMain.Modified)
goto default;
else
goto case DialogResult.No;
case DialogResult.No:
this.Dispose(true);
break;
default:
e.Cancel = true;
break;
}
}
else
this.Dispose(true);
}
else
this.Dispose(true);//释放所有使用的资源。如果没有这一句,窗口可以关闭啊!但是在占用资源。
}
private void menuNew_Click(object sender, EventArgs e)
{
if (textBoxMain.Modified)
{
if (filePath.Length != 0 || textBoxMain.Text.Length != 0)
{
string showInfo = "文件 {0} 的文字已经改变。\r\n\r\n想保存文件吗?";
if (filePath.Length == 0)
showInfo = string.Format(showInfo, fileTitle);
else
showInfo = string.Format(showInfo, filePath);
switch (MessageBox.Show(showInfo, caption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning))
{
case DialogResult.Yes:
SaveFile();
if (textBoxMain.Modified)
goto default;
else
goto case DialogResult.No;
case DialogResult.No:
NewFile();
break;
default:
break;
}
}
else
NewFile();
}
else
NewFile();
}
private void menuOpen_Click(object sender, EventArgs e)
{
if (textBoxMain.Modified)
{
if (filePath.Length != 0 || textBoxMain.Text.Length != 0)
{
string showInfo = "文件 {0} 的文字已经改变。\r\n\r\n想保存文件吗?";
if (filePath.Length == 0)
showInfo = string.Format(showInfo, fileTitle);
else
showInfo = string.Format(showInfo, filePath);
switch (MessageBox.Show(showInfo, caption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning))
{
case DialogResult.Yes:
SaveFile();
if (textBoxMain.Modified)
goto default;
else
goto case DialogResult.No;
case DialogResult.No:
OpenFile();
break;
default:
break;
}
}
else
OpenFile();
}
else
OpenFile();
}
private void menuSave_Click(object sender, EventArgs e)
{
SaveFile();
}
private void menuSaveAs_Click(object sender, EventArgs e)
{
SaveAsFile();
}
private void menuPageSetup_Click(object sender, EventArgs e)
{
}
private void menuPrint_Click(object sender, EventArgs e)
{
}
private void menuExit_Click(object sender, EventArgs e)
{
this.Dispose(true);
Application.Exit();
}
private void menuUndo_Click(object sender, EventArgs e)
{
textBoxMain.Undo();
}
private void menuCut_Click(object sender, EventArgs e)
{
textBoxMain.Cut();
}
private void menuCopy_Click(object sender, EventArgs e)
{
textBoxMain.Copy();
}
private void menuPaste_Click(object sender, EventArgs e)
{
textBoxMain.Paste();
}
private void menuDelete_Click(object sender, EventArgs e)
{
textBoxMain.SelectedText = "";//无法撤销
textBoxMain.Modified = true;//哎!这行让我绕个大圈。
}
private void menuFind_Click(object sender, EventArgs e)
{
new FindForm().Show(this);
}
private void menuFindNext_Click(object sender, EventArgs e)
{
}
private void menuReplace_Click(object sender, EventArgs e)
{
new ReplaceForm().Show(this);
}
private void menuGoto_Click(object sender, EventArgs e)
{
new GotoForm().ShowDialog(this);
}
private void menuSelectAll_Click(object sender, EventArgs e)
{
textBoxMain.SelectAll();
}
private void menuDateTime_Click(object sender, EventArgs e)
{
textBoxMain.AppendText(DateTime.Now.ToString("HH:mm:ss yyyy-M-d"));
}
private void menuWordWrap_Click(object sender, EventArgs e)
{
textBoxMain.WordWrap = !textBoxMain.WordWrap;
menuWordWrap.Checked = !menuWordWrap.Checked;
if (menuWordWrap.Checked)
{
menuStatus.Checked = false;
menuStatus.Enabled = false;
statusStripMain.Visible = false;
}
else
menuStatus.Enabled = true;
}
private void menuFont_Click(object sender, EventArgs e)
{
fontDlg.Font = textBoxMain.Font;
if (fontDlg.ShowDialog() == DialogResult.OK)
textBoxMain.Font = fontDlg.Font;
}
private void menuStatus_Click(object sender, EventArgs e)
{
statusStripMain.Visible = !statusStripMain.Visible;
menuStatus.Checked = !menuStatus.Checked;
}
private void menuHelpContext_Click(object sender, EventArgs e)
{
string notepadHelpFile = Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), @"Help\notepad.chm");//可能引发异常
if (File.Exists(notepadHelpFile))
Help.ShowHelp(this, notepadHelpFile);//可能引发异常
else
{
string showInfo = "帮助文件不存在。";
MessageBox.Show(showInfo, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void menuAbout_Click(object sender, EventArgs e)
{
aboutBox.ShowDialog(this);//可能引发异常
}
private void menuGB2312_Click(object sender, EventArgs e)
{
fileEncoding = Encoding.GetEncoding(936);
}
private void menuGB18030_Click(object sender, EventArgs e)
{
fileEncoding = Encoding.GetEncoding(54936);
}
private void menuUnicode_Click(object sender, EventArgs e)
{
fileEncoding = Encoding.Unicode;
}
private void menuUnicodeBE_Click(object sender, EventArgs e)
{
fileEncoding = Encoding.BigEndianUnicode;
}
private void menuUTF32_Click(object sender, EventArgs e)
{
fileEncoding = Encoding.UTF32;
}
private void menuUTF32BE_Click(object sender, EventArgs e)
{
fileEncoding = Encoding.GetEncoding(12001);
}
private void menuUTF8_Click(object sender, EventArgs e)
{
fileEncoding = Encoding.UTF8;
}
private void menuUTF7_Click(object sender, EventArgs e)
{
fileEncoding = Encoding.UTF7;
}
private void statusStripMain_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
labelTextModified.Visible = labelTextEncoding.Visible = menuEncoding.Visible = !menuEncoding.Visible;
}
}
}
温馨提示:答案为网友推荐,仅供参考