前言
WinForm使用C#语言做一个简单的记事本,满足加载、保存文件,编辑文本、修改文本字体和颜色功能。
一、运行使用效果
二、界面设计
- menuscript控件
- ToolScriptMenuItem
- RichTextBox
msMain、tsmiFile、tsmiOpen、tsmiOpenFile、tsmiOpenDirectory、tsmiSave、tsmiEdit、tsmiBackColor、tsmiFont、tsmiAbout、rtbEditor
三、代码
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 NotePadForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
openFileDialog1.Filter = "文本文件(*.txt)|*.txt|富文本文件(*.rtf)|*.rtf";
saveFileDialog1.Title = "另存为";
saveFileDialog1.Filter = "文本文件(*.txt)|*.txt|富文本文件(*.rtf)|*.rtf";
}
//打开文件
private void tsmiOpenFile_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
string fileName = openFileDialog1.FileName;
if (fileName.EndsWith(".txt", true, null))
{
rtbEditor.LoadFile(fileName, RichTextBoxStreamType.PlainText);
}
else
{
rtbEditor.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//打开文件夹
private void tsmiOpenDirectory_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
try
{
openFileDialog1.InitialDirectory = folderBrowserDialog1.SelectedPath;
saveFileDialog1.InitialDirectory = folderBrowserDialog1.SelectedPath;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//保存文件
private void tsmiSave_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if (saveFileDialog1.FileName.EndsWith("", true, null))
{
rtbEditor.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
else
{
rtbEditor.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//设置背景颜色
private void tsmiBackColor_Click(object sender, EventArgs e)
{
colorDialog1.Color = rtbEditor.SelectionBackColor;
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
try
{
rtbEditor.SelectionBackColor = colorDialog1.Color;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//更改字体
private void tsmiFont_Click(object sender, EventArgs e)
{
fontDialog1.Font = rtbEditor.SelectionFont;
fontDialog1.Color = rtbEditor.SelectionColor;
if (fontDialog1.ShowDialog() == DialogResult.OK)
{
rtbEditor.SelectionFont = fontDialog1.Font;
rtbEditor.SelectionColor = fontDialog1.Color;
}
}
private void tsmiAbout_Click(object sender, EventArgs e)
{
AboutForm about = new AboutForm();
about.ShowDialog();
}
private void tsmiEdit_DropDownOpening(object sender, EventArgs e)
{
if (rtbEditor.SelectionLength == 0)
{
tsmiBackColor.Enabled = false;
tsmiFont.Enabled = false;
}
else
{
tsmiBackColor.Enabled = true;
tsmiFont.Enabled = true;
}
}
}
}
总结
WinForm做的一个简单版本记事本。