94 lines
2.5 KiB
C#
94 lines
2.5 KiB
C#
using System;
|
|
using System.Net.Security;
|
|
using System.Reflection;
|
|
using static System.Net.Mime.MediaTypeNames;
|
|
|
|
namespace Metoder
|
|
{
|
|
public partial class Form1 : Form
|
|
{
|
|
public Form1()
|
|
{
|
|
InitializeComponent();
|
|
}
|
|
|
|
private void btn_find_Click(object sender, EventArgs e)
|
|
{
|
|
string searchWord = txtbx_find.Text;
|
|
Highlight(searchWord);
|
|
}
|
|
|
|
private void btn_clear_Click(object sender, EventArgs e)
|
|
{
|
|
lbl_found.Visible = false;
|
|
}
|
|
|
|
void UpdateFindResult(int foundCount)
|
|
{
|
|
lbl_found.Visible = true;
|
|
string suffix;
|
|
|
|
// correct grammar
|
|
if (foundCount == 1)
|
|
suffix = " item found";
|
|
else
|
|
suffix = " items found";
|
|
|
|
lbl_found.Text = foundCount.ToString() + suffix;
|
|
}
|
|
|
|
(int start, int length) FindTextIndex(string text, int startIndex)
|
|
{
|
|
int start = (text.IndexOf(text, startIndex, StringComparison.OrdinalIgnoreCase));
|
|
if (start == -1) return (-1, 0);
|
|
|
|
return (start, text.Length);
|
|
}
|
|
|
|
void Highlight(string word)
|
|
{
|
|
if (word == "") return; // avoid errors, infinite loop
|
|
|
|
RichTextBox richTextBox = txtbx_text;
|
|
string text = richTextBox.Text;
|
|
|
|
// reset old highlight
|
|
richTextBox.SelectAll();
|
|
richTextBox.SelectionBackColor = richTextBox.BackColor;
|
|
|
|
int found = 0;
|
|
int caret = richTextBox.SelectionStart; // set cursor
|
|
|
|
var words = GetWords();
|
|
int index = 0;
|
|
|
|
while ((index = text.IndexOf(word, index, StringComparison.OrdinalIgnoreCase)) != -1)
|
|
{
|
|
richTextBox.Select(index, word.Length); // select word
|
|
richTextBox.SelectionBackColor = Color.LightBlue;
|
|
found++; // count found
|
|
index = index + word.Length; // offset (ignore word next loop)
|
|
}
|
|
|
|
// reset cursor
|
|
richTextBox.Select(caret, 0);
|
|
|
|
// update find label
|
|
UpdateFindResult(found);
|
|
}
|
|
|
|
List<string> GetWords() // get list of words separated by spaces
|
|
{
|
|
string text = txtbx_text.Text;
|
|
string[] words = text.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
|
|
|
|
return words.ToList();
|
|
}
|
|
|
|
private void btn_replace_Click(object sender, EventArgs e)
|
|
{
|
|
|
|
}
|
|
}
|
|
}
|