软件:Visual Studio 2019
项目名:WindowsFormsApp12
一.窗体设计
从工具栏添加3个Label、3个TextBox、6个Button、1个RichTextBox(ScrollBars属性为ForcedVertical)到窗体中,如下图所示:
二.代码
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 WindowsFormsApp12
{
public partial class Form1 : Form
{
string path;
int start = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)//打开按钮
{
path = Application.StartupPath + "\\" + textBox1.Text;//完整路径名
richTextBox1.LoadFile(path, RichTextBoxStreamType.RichText);//读取
}
private void button2_Click(object sender, EventArgs e)//保存按钮
{
richTextBox1.SaveFile(path, RichTextBoxStreamType.RichText);
}
private void button3_Click(object sender, EventArgs e)//查找按钮
{
start = richTextBox1.Find(textBox2.Text.Trim());
richTextBox1.Focus();
}
private void button4_Click(object sender, EventArgs e)//替换按钮
{
start = start + textBox2.Text.Length;
richTextBox1.SelectedText = textBox3.Text;
richTextBox1.Focus();
}
private void button5_Click(object sender, EventArgs e)//查找下一个按钮
{
string strfind;
strfind = textBox2.Text;
start = start + strfind.Length;
start = richTextBox1.Find(strfind, start, RichTextBoxFinds.None);
if (start < 0)
MessageBox.Show("已经搜索到文件末尾!");
richTextBox1.Focus();
}
private void button6_Click(object sender, EventArgs e)//替换全部按钮
{
richTextBox1.Text = richTextBox1.Text.Replace(textBox2.Text, textBox3.Text);
}
}
}
三.注意事项
关于RTF文件的路径,如下图所示: