2009-09-18 5 views
0

Dans un Windows Form, en utilisant C#, comment sélectionner (comme dans, mettre en évidence le texte, le rendre accessible à la propriété .SelectedText) un mot basé sur l'emplacement du curseur?C# | Comment puis-je sélectionner un mot dans un TextBox par emplacement du curseur?

Voici ce que j'essaie de faire. J'ai une zone de texte que les utilisateurs peuvent actuellement sélectionner un mot en le mettant en évidence. Ils peuvent ensuite effectuer diverses actions sur le mot, mais je veux le rendre plus simple.

Je souhaite faire en sorte qu'ils puissent simplement mettre le curseur dans le mot et l'application va sélectionner le mot que le curseur est à l'intérieur de.

Merci d'avance!

Répondre

4

Vous pouvez utiliser SelectionStart et SelectionLength mais vous avez probablement besoin de trouver l'espace suivant de la position du curseur, puis d'inverser le contenu de la zone de texte et trouver le prochain « espace » de la position « curseur modifié », puis utilisez les deux méthodes ci-dessus.

Cela permettra également travailler

int cursorPosition = textBox1.SelectionStart; 
int nextSpace = textBox1.Text.IndexOf(' ', cursorPosition); 
int selectionStart = 0; 
string trimmedString = string.Empty; 
// Strip everything after the next space... 
if (nextSpace != -1) 
{ 
    trimmedString = textBox1.Text.Substring(0, nextSpace); 
} 
else 
{ 
    trimmedString = textBox1.Text; 
} 


if (trimmedString.LastIndexOf(' ') != -1) 
{ 
    selectionStart = 1 + trimmedString.LastIndexOf(' '); 
    trimmedString = trimmedString.Substring(1 + trimmedString.LastIndexOf(' ')); 
} 

textBox1.SelectionStart = selectionStart; 
textBox1.SelectionLength = trimmedString.Length; 
+0

fonctionne très bien. Je vous remercie. – Chaddeus

2

Utilisez les propriétés SelectionStart et SelectionLength.
google

+0

hmm ... Je peux obtenir l'emplacement du curseur avec SelectionStart. Et s'ils mettent le curseur au milieu du mot (ce qui est plus probable dans mon cas). Je ne suis pas clair sur la façon de sélectionner réellement le mot. (Je viens d'un contexte de développement web ...). Merci d'avance. – Chaddeus

+0

Utilisez le .Text et recherchez les espaces: par exemple: int startWord = box.SelectionStart; while (box.Text [startWord]! = '') {StartWord--; } – tster

0

Hope this helps:

  if (string.IsNullOrEmpty(textBox1.Text)) 
     { 
      return; 
     } 

     int cursorPos = textBox1.SelectionStart; 
     int firstPos = 0; 
     int lastPost = 0; 

     // If the current cursor is at the end of the string, try to go backwards 
     string currentChar = cursorPos == textBox1.Text.Length ? textBox1.Text.Substring(cursorPos - 1, 1) : textBox1.Text.Substring(cursorPos, 1); 
     if (currentChar == " ") 
     { 
      cursorPos--; 
     } 

     // Iterate to the first position where a space is 
     for (int i = cursorPos; i > 0; i--) 
     { 
      // Get the current character 
      currentChar = i == textBox1.Text.Length ? textBox1.Text.Substring(i - 1, 1) : textBox1.Text.Substring(i, 1); 
      if (currentChar == " ") 
      { 
       firstPos = i+1; 
       break; 
      } 
     } 

     for (int i = cursorPos; i <= textBox1.Text.Length; i++) 
     { 
      if (i == textBox1.Text.Length) 
      { 
       lastPost = i; 
      } 
      else 
      { 
       // Get the current character 
       currentChar = textBox1.Text.Substring(i, 1); 
       if (currentChar == " ") 
       { 
        lastPost = i; 
        break; 
       } 
      } 
     } 

     textBox1.SelectionStart = firstPos; 
     textBox1.SelectionLength = lastPost - firstPos; 
     textBox1.Focus(); 

Pour cet exemple, vous avez besoin d'une zone de texte, textBox1 et un bouton l'emplacement du code. Dites-moi si vous avez besoin d'aide.

EDIT: Modification d'un peu du code et test de tous les scénarios. J'espère que cela aide!

+0

Merci, j'essaie maintenant. – Chaddeus

+0

Fonctionne bien! Sauf, si l'utilisateur quitte le curseur à la fin d'un mot. Il lance une ArgumentOutOfRangeException à partir de la sous-chaîne en essayant de trouver firstPos. – Chaddeus

+0

Et, il n'y a pas d'autres caractères dans la zone de texte ... – Chaddeus

0

en fait j'ai obtenu une approche plus simple ici

Dim intCursor As Integer = txtInput.SelectionStart 
Dim intStart As Int32 = CInt(IIf(intCursor - 1 < 0, 0, intCursor - 1)) 
Dim intStop As Int32 = intCursor 
intStop = txtInput.Text.IndexOf(" ", intCursor) 
intStart = txtInput.Text.LastIndexOf(" ", intCursor) 
If intStop < 0 Then 
intStop = txtInput.Text.Length 
End If 
If intStart < 0 Then 
    intStart = 0 
End If 
debug.print(txtInput.Text.Substring(intStart, intStop - intStart).Trim) 
+0

possible de le faire dans jQuery par hasard? :) – Chaddeus

1
//this is our article 
string article = " " + richTextBox1.Text.ToLower() + " "; 
//we search the word from textbox1 
        int middle = article.IndexOf(textBox1.Text); 
        int headOfWord = article.LastIndexOf(" ", middle); 
        int tailOfWord = article.IndexOf(" ", middle); 
    //we have found the head and tail of the word 
        textBox2.Text = article.Substring(headOfWord, tailOfWord - headOfWord); 
        richTextBox1.Focus(); 
        richTextBox1.Select(headOfWord, tailOfWord - headOfWord - 1); 
Questions connexes