Search code examples
c#.netwinformstextboxtooltip

Display Tooltip over cursor in textbox


I am working on a project in Winforms (.NET Framework 4.7.2), and would like to display a bubble tooltip over the cursor in a textbox control. This is what I currently have:

What I currently have

And this is what I would like:

What I would like

I have tried both SetToolTip() and Tooltip.Show() methods, but I cannot make the tooltip display over the textbox cursor. How do I accomplish this?


Solution

  • You can get the cursor (caret) position using the win32 function GetCaretPos and then pass that position to the ToolTip.Show() method.

    First, add the following to your class (preferably, a separate static class for native methods):

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetCaretPos(out Point lpPoint);
    

    Then, you can do something like this:

    ToolTip tTip = new ToolTip();
    tTip.IsBalloon = true;
    tTip.ToolTipIcon = ToolTipIcon.Error;
    tTip.ToolTipTitle = "Your title";
    
    Point p;
    if (GetCaretPos(out p))
    {
        // This is optional. Removing it causes the arrow to point at the top of the line.
        int yOffset = textBox1.Font.Height;
        p.Y += yOffset;
    
        // Calling .Show() two times because of a known bug in the ToolTip control.
        // See: https://stackoverflow.com/a/4646021/4934172
        tTip.Show(string.Empty, textBox1, 0);
        tTip.Show("Your message here", textBox1, p, 1000);
    }
    

    Note:

    I called the ToolTip.Show() method twice, the first time with an empty string and a duration of 0 ms because of a known bug in the ToolTip control which causes the balloon arrow not to point to the right place the first time it's called. Check this answer for more info.