2014-03-27 21 views
2

我正在製作一個Windows記事本的副本,並且我被困在「查找」功能中。老實說,我不知道如何做到這一點。我一直在尋找一段時間,每個人都建議RichTextBox,因爲它已經實現了查找功能,但重點是我需要使用文本框。使用C中的TextBox爲記事本設置查找功能

所以我製作了新的表格,將它與主表單連接起來。我做的類看起來像:

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(); 

而且我知道我必須做的,但我不知道該代碼吧..任何幫助,將不勝感激! TY

回答

1

你會通常使用String.IndexOf找到文本框中匹配的位置。這將允許您使用TextBox.SelectionStartSelectionLength來設置選擇。

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超載,它允許您指定一個起點,這將更容易處理。

+0

感謝。我在哪裏運行此方法?在我的發現形式或我的主要形式?我很困惑 –

+0

@KristijanDelivuk那麼,這需要訪問主窗體的文本框... –

+0

是啊我明白了,但後來當我在我的程序的Find_form我需要調用按鈕按下這種方法,我打電話給它函數: ((Notepad_form)this.Owner).FindAndSelect()...但編譯器不想執行該行...我已經使Find_Form.Owner = this;在我的主類,所以我不明白爲什麼我不能看到方法 –

0

開始,嘗試這樣的事情,在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; 
} 
0

私人無效b1_Click(對象發件人,EventArgs的) {

 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"); 
      } 

     } 
+1

請解釋一下,你的代碼如何解決問題中的問題。此外,編輯您的答案以修復您的代碼塊(我會這樣做,但編輯隊列已滿)。 –