在C#中,你可以使用Windows Forms或WPF(Windows Presentation Foundation)来创建一个简单的记事本应用程序。以下是一个简单的Windows Forms记事本示例:
首先,打开Visual Studio并创建一个新的Windows Forms应用程序项目。
在解决方案资源管理器中,双击“Form1.cs”以打开设计器。
从工具箱中,将以下控件添加到表单上:
为MenuStrip控件添加以下菜单项:
为这些菜单项添加Click事件处理程序。
在Form1.cs中,为每个菜单项的Click事件添加以下代码:
using System;
using System.IO;
using System.Windows.Forms;
namespace Notepad
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Clear();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string fileContent = File.ReadAllText(openFileDialog.FileName);
textBox1.Text = fileContent;
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog.FileName, textBox1.Text);
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Cut();
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Copy();
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Paste();
}
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.SelectedText = "";
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Simple Notepad application created in C#", "About");
}
}
}
这只是一个简单的示例,你可以根据需要添加更多功能,例如字体选择、颜色选择、搜索和替换等。