6. 搜尋字串並標示黃色背景顏色
namespace Q6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "txt files (*.txt)|*.txt";
openFileDialog1.ShowDialog();
richTextBox1.Text = new StreamReader(openFileDialog1.OpenFile()).ReadToEnd();
}
private void button1_Click(object sender, EventArgs e)
{
var to = textBox1.Text;
if (to.Length == 0)
{
MessageBox.Show("未輸入欲搜尋的字串");
return;
}
int i = 0;
int n = 0;
richTextBox1.SelectAll();
richTextBox1.SelectionBackColor = Color.White;
while ((i = richTextBox1.Text.IndexOf(to, i)) != -1)
{
richTextBox1.Select(i, to.Length);
richTextBox1.SelectionBackColor = Color.Yellow;
i = i + to.Length;
n++;
}
amt.Text = n.ToString();
}
}
}
Last updated