在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");
}
}
}
這只是一個簡單的示例,你可以根據需要添加更多功能,例如字體選擇、顏色選擇、搜索和替換等。