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

标签 c# .net winforms textbox mouse-position

我有一个多行文本框,它根据给定的数据显示一些值(通常每行一个值)。

(为了让工具提示弹出一些“替代”数据)我想得到鼠标悬停在上面的词(或者至少是一行),这样我就可以找到替代方法显示。

关于如何根据文本框和字体大小进行计算,我有一些想法,但我不知道该怎么做,因为大小和字体可能会经常变化。

那么...有什么方法可以使用鼠标位置来抓取特定的文本框文本吗?

最佳答案

这是一个替代解决方案。将此 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/

相关文章:

c# - 如何阻止所有键盘和鼠标输入到我的 WinForms 应用程序?

c# - 隐藏具有关联属性的输入标签

c# - 正则表达式 - MARK 以查看匹配的捕获组

c# - 尝试使用 angularJS 和 c# webapi 从服务器下载文件

c# - 在 XP 上,如何使工具提示显示在半透明表单上方?

c# - 使用 KeyPressEvent 抑制按键 "Bing"?

c# - 查询删除 logdatetime 范围内的日志

c# - 多线程谜语的更好解决方案?

c# - 选择 Table.Value == 最大值

c# - 使用 Windows 文件复制或文件移动动画?