如何根据鼠标位置从文本框中获取特定的文本值 [英] How to get specific text value from a textbox based upon the mouse position

查看:177
本文介绍了如何根据鼠标位置从文本框中获取特定的文本值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多行文本框,根据输入的数据显示一些值(通常每行一个值).

I have a multi-line text box that displays some values based on data it gets given, (Generally one value per line).

(出于弹出带有一些替代"数据的工具提示的目的),我想知道鼠标悬停在上面的字词(或至少是该行),以便于我找到替代方法.显示.

(For the purpose of having a tool tip popup with some 'alternative' data) I would like to get the word (or at the very least the line) that the mouse is hovering over so I can then find what alternative to display.

我对如何基于文本框和字体大小进行计算有一些想法,但是由于大小和字体可能会经常更改,因此我不打算这样做.

I have a few ideas of how to do this with calculations based on the text box and font sizes but I do not what to go down this road as the sizes and fonts may change frequently.

那么...有什么办法可以利用鼠标的位置来获取特定的文本框文本?

So... Is there any way of using the mouses position to grab specific text box text?

推荐答案

这是另一种解决方案.将此MouseMove事件添加到您的文本框:

Here's an alternate solution. Add this MouseMove event to your TextBox:

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;
    toolTip.SetToolTip(targetTextBox, currentWord);
}

这篇关于如何根据鼠标位置从文本框中获取特定的文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆