Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get specific text value from a textbox based upon the mouse position

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?

like image 817
Jammerz858 Avatar asked Oct 25 '12 14:10

Jammerz858


People also ask

How to set focus at the end of TextBox in c#?

To position the cursor at the end of the contents of a TextBox control, call the Select method and specify the selection start position equal to the length of the text content, and a selection length of 0.

How do I find my cursor position?

Once you're in Mouse settings, select Additional mouse options from the links on the right side of the page. In Mouse Properties, on the Pointer Options tab, at the bottom, select Show location of pointer when I press the CTRL key, and then select OK. To see it in action, press CTRL.

How can I move cursor from one TextBox to another in C#?

Take a look at the Tabindex property. It can be set from the Properties window of the control so if Tabindex is 2, then the tab key has to be pressed 2 times to reach that control.

How do I get the cursor position in Python?

To determine the mouse's current position, we use the statement, pyautogui. position(). This function returns a tuple of the position of the mouse's cursor. The first value is the x-coordinate of where the mouse cursor is.


1 Answers

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);
}
like image 181
Michael Sallmen Avatar answered Sep 17 '22 15:09

Michael Sallmen