在c#中为带有文本框的记事本创建查找功能
本文关键字:记事本 创建 查找 功能 文本 | 更新日期: 2023-09-27 17:54:28
我正在复制Windows记事本,我被卡在"FIND"功能上。老实说,我不知道怎么做。我一直在搜索一段时间,每个人都建议RichTextBox,因为它已经实现了查找功能,但重点是我需要使用文本框。
所以我做了一个新的表单,把它和主表单连接起来。我创建了如下的类:
public bool FindAndSelect(string TextToFind, bool MatchCase, bool UpDown)
{
}
但是我不知道写什么才能起作用。我已经使查找按钮在查找形式与功能
if (((fNotepad)this.Owner).FindAndSelect(this.textBoxFind.Text, this.rbUpDown.Checked, this.cbMatchCase.Checked) == false)
{
MessageBox.Show("Cant find selected text");
}
else this.Close();
我知道我要做什么,但我不知道如何编码…任何帮助将不胜感激!泰
您通常使用String。在文本框中查找匹配项的位置。这将允许您使用文本框。选择start和SelectionLength
设置选择
public bool FindAndSelect(string TextToFind, bool MatchCase)
{
var mode = MatchCase ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
int position = textBox.Text.IndexOf(TextToFind, mode);
if (position == -1)
return false;
textBox.SelectionStart = position;
textBox.SelectionLength = TextToFind.Length;
return true;
}
注意上面没有处理"上/下"-要做到这一点,您需要与当前SelectionStart
位置进行比较,并查看之后是否有匹配。有一个IndexOf的重载,它允许您指定一个起始点,这将使它更容易处理。
首先,在btnFind_Click事件中尝试这样做:
private btnFind_Click(Object sender, EventArgs e)
{
if(CountStringOccurrences(txtNotePad.Text, txtToFind.Text) > 0)
{
MessageBox.Show("Found 1 or multiple matches");
}
else
{
MessageBox.Show("Didn't found match...");
}
}
//CountStringOccurrences, takes full text + string to match with
//Returns the amount of matches found in full text
public static int CountStringOccurrences(string text, string pattern)
{
// Loop through all instances of the string 'text'.
int count = 0;
int i = 0;
while ((i = text.IndexOf(pattern, i)) != -1)
{
i += pattern.Length;
count++;
}
return count;
}
private void b1_Click(对象发送者,EventArgs e){
string[] a = new string[100];`
string word = tb.Text;
WinFormsApp2.Form1 fi = new WinFormsApp2.Form1();
for (int i = 0; i < 100; i++)
{
if (word == fi.find[i])
{
MessageBox.Show("FOUNDED");
}
}