Как получить текущее слово в позиции каретки из строки (TextBox), в которой есть клавиши ПРОБЕЛ и ВВОД? - PullRequest
1 голос
/ 23 марта 2011

Как получить текущее слово в позиции курсора из TextBox, который будет содержать "" и "\ r \ n" как разделитель слов?

Ответы [ 3 ]

1 голос
/ 15 декабря 2013

Я использую это, чтобы выбрать слово:

    private void selectWord()
    {
        int cursorPosition = textBox1.SelectionStart;
        int nextSpace = textBox1.Text.IndexOf(' ', cursorPosition);
        int selectionStart = 0;
        string trimmedString = string.Empty;
        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;
    }

, и это, чтобы получить выбранное слово:

textBox1.SelectedText
1 голос
/ 23 марта 2011

Что-то похожее на это должно работать:

var currentWord = textBox.Text.Substring(textBox.SelectionStart, textBox.Text.IndexOf(" ", textBox.SelectionStart));
0 голосов
/ 17 мая 2018

У меня есть эта проблема сейчас, и вот мой подход к решению этой проблемы. TxtLineCodes - это RichTextBox элемент управления. Пожалуйста, смотрите мои комментарии внутри кода.

private void CheckCurrentWord()
{
    // current caret position
    var currentposition = TxtLineCodes.SelectionStart;
    // get line number
    var linenumber = TxtLineCodes.GetLineFromCharIndex(currentposition);
    // get the first character index of the line
    var firstlineindex = currentposition;
    if (linenumber == 0)
    {
        firstlineindex = 0;
    }
    else
    {
        while (TxtLineCodes.GetLineFromCharIndex(firstlineindex) == linenumber)
        {
            firstlineindex--;
        }
        //fix the last iteration
        firstlineindex += 1;
    }

    // if caret is not in the end of the word discover it
    var lastcaretwordindex = currentposition;
    if (lastcaretwordindex < TxtLineCodes.Text.Length)
        while (lastcaretwordindex < TxtLineCodes.Text.Length && TxtLineCodes.Text.Substring(lastcaretwordindex, 1) != " ")
        {
            lastcaretwordindex += 1;
        }

    // get the text of the line (until the cursor position)
    var linetext = TxtLineCodes.Text.Substring(firstlineindex, lastcaretwordindex - firstlineindex);
    // split all the words in current line
    string[] words = linetext.Split(' ');
    // the last word must be the current word
   System.Diagnostics.Debug.WriteLine("current word: " + words[words.Length - 1]);
    // and you can also get the substring indexes of the current word
    var currentwordbysubstring = TxtLineCodes.Text.Substring(lastcaretwordindex - words[words.Length - 1].Length, words[words.Length - 1].Length);

    var startindex = lastcaretwordindex - words[words.Length - 1].Length;
    var lastindex = startindex + words[words.Length - 1].Length-1;
    System.Diagnostics.Debug.WriteLine("current word: " + currentwordbysubstring + " and its in index (" + startindex + "," + lastindex + ")");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...