获取光标下的单词我的错误是什么?

时间:2013-03-26 13:15:38

标签: c# textbox mouseevent mouseover getchar

我的错误是什么?我想在网站上对textbox2说一句话。对不起,因为我的坏工程。 :)

private void txtHoverWord_MouseMove(object sender, MouseEventArgs e){
    if (!(sender is TextBox)) return;
    var targetTextBox = sender as TextBox;
    if (targetTextBox.TextLength < 1) return;

    var currentTextIndex = textBox2.GetCharIndexFromPosition(e.Location);
    var wordRegex = new Regex(@"(\w+)");
    var words = wordRegex.Matches(textBox2.Text);
    if (words.Count < 1) return;

    var currentWord = string.Empty;
    for (var i = words.Count - 1; i >= 0; i--)
    {
        if (words[i].Index <= currentTextIndex)
        {
            currentWord = words[i].Value;
            break;
        }
    }

    if (currentWord == string.Empty) return;
    toolTip1.SetToolTip(textBox2, currentWord);
}

1 个答案:

答案 0 :(得分:0)

我相信您可能在代码中无意中指定了textBox2而不是targetTextBox

尝试将其修改为以下内容:

private void txtHoverWord_MouseMove(object sender, MouseEventArgs e)
{
    if (!(sender is TextBox)) return;
    var targetTextBox = sender as TextBox;
    if (targetTextBox.TextLength < 1) return;

    var currentTextIndex = targetTextBox.GetCharIndexFromPosition(e.Location);
    var wordRegex = new Regex(@"(\w+)");
    var words = wordRegex.Matches(targetTextBox.Text);
    if (words.Count < 1) return;

    var currentWord = string.Empty;
    for (var i = words.Count - 1; i >= 0; i--)
    {
        if (words[i].Index <= currentTextIndex)
        {
            currentWord = words[i].Value;
            break;
        }
    }

    if (currentWord == string.Empty) return;
    tooltip1.SetToolTip(targetTextBox, currentWord);
}

注意我将textBox2更改为targetTextBox,无论它出现在您的代码中。