C # | Come posso selezionare una parola in una casella di testo in base alla posizione del cursore?

StackOverflow https://stackoverflow.com/questions/1442360

  •  22-07-2019
  •  | 
  •  

Domanda

In un Windows Form, usando C #, come posso selezionare (come in, evidenziare effettivamente il testo, rendendolo accessibile alla proprietà .SelectedText) una parola in base alla posizione del cursore?

Ecco cosa sto cercando di fare. Ho una casella di testo che gli utenti possono attualmente selezionare una parola evidenziandola. Possono quindi eseguire varie azioni sulla parola, ma voglio renderla più semplice.

Vorrei farlo in modo che possano semplicemente posizionare il cursore all'interno della parola e l'app selezionerà la parola in cui si trova il cursore.

Grazie in anticipo!

È stato utile?

Soluzione

Puoi usare SelectionStart e SelectionLength ma probabilmente dovrai trovare lo spazio successivo dalla posizione del cursore, quindi invertire il contenuto della casella di testo e trovare il successivo " spazio " dal cursore "modificato" " posizione, quindi utilizzare i due metodi sopra.

Funzionerà anche

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;

Altri suggerimenti

Utilizza le proprietà SelectionStart e SelectionLength.
google

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

Spero che questo aiuti:

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

Per questo esempio, hai bisogno di una casella di testo, textBox1 e un pulsante dove va questo codice. Fammi sapere se hai bisogno di aiuto.

EDIT: ha cambiato un po 'il codice e testato tutti gli scenari. Spero che sia d'aiuto!

in realtà ho un approccio più semplice qui

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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top