我有一个多行文本框,它根据给定的数据显示一些值(通常每行一个值)。
(为了让工具提示弹出一些“替代”数据)我想得到鼠标悬停在上面的词(或者至少是一行),这样我就可以找到替代方法显示。
关于如何根据文本框和字体大小进行计算,我有一些想法,但我不知道该怎么做,因为大小和字体可能会经常变化。
那么...有什么方法可以使用鼠标位置来抓取特定的文本框文本吗?
最佳答案
这是一个替代解决方案。将此 MouseMove 事件添加到您的文本框:
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);
}
关于c# - 如何根据鼠标位置从文本框中获取特定文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13070841/