需求如下:
效果预览:

创建 Winform 项目并设计界面

编写代码实现切换逻辑
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace 文本
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog()
{
Title = "打开文件",
Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*",
InitialDirectory = "C:\\Users\\Administrator\\Desktop"
};
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string directory = openFileDialog.FileName;// 目录
string fileName = openFileDialog.SafeFileName;// 文件
try
{
using (StreamReader sr = new StreamReader(directory, Encoding.UTF8))
{
textBox1.Clear();
textBox1.Text = sr.ReadToEnd();
}
}
catch (Exception)
{
MessageBox.Show("打开文件失败");
}
}
}
private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog()
{
Title = "保存文件",
Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*",
InitialDirectory = "E:/桌面",
DefaultExt = ".txt",
OverwritePrompt = true,
};
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
string filePath = saveFileDialog.FileName;
File.WriteAllText(filePath, textBox1.Text);
textBox1.Clear();// 清空输入框中的信息
MessageBox.Show("文件保存成功!");
}
catch (Exception)
{
MessageBox.Show("保存文件失败");
}
}
}
private void 自动换行ToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.WordWrap = true;
MessageBox.Show("开启自动换行");
}
private void 取消ToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.WordWrap = false;
MessageBox.Show("关闭自动换行");
}
private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
{
FontDialog fontDialog = new FontDialog();
if (fontDialog.ShowDialog() == DialogResult.OK)
{
textBox1.Font = fontDialog.Font;
MessageBox.Show("字体样式设置成功!");
}
else
{
MessageBox.Show("取消设置字体样式");
}
}
private void 颜色ToolStripMenuItem_Click(object sender, EventArgs e)
{
ColorDialog colorDialog = new ColorDialog();
if (colorDialog.ShowDialog() == DialogResult.OK)
{
textBox1.ForeColor = colorDialog.Color;
}
else
{
MessageBox.Show("取消颜色设置");
}
}
}
}
效果演示

1147



被折叠的 条评论
为什么被折叠?



