c# – 如何根据鼠标位置从文本框获取特定的文本值

前端之家收集整理的这篇文章主要介绍了c# – 如何根据鼠标位置从文本框获取特定的文本值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个多行文本框,根据给定的数据显示一些值(通常每行一个值).

(为了使工具提示弹出一些“替代”数据),我想得到鼠标悬停的单词(或至少在行上),以便我可以找到显示的替代方法.

我有几个想法,如何做到这一点基于文本框和字体大小的计算,但我不会下去这条路,因为大小和字体可能会频繁更改.

所以…有没有办法使用鼠标位置来抓取特定的文本框文本?

解决方法

这是一个替代解决方案.将此MouseMove事件添加到您的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);
}
原文链接:https://www.f2er.com/csharp/95533.html

猜你在找的C#相关文章