Knowing the point location of the caret in a Winforms TextBox?

前端 未结 7 1704
粉色の甜心
粉色の甜心 2021-01-12 08:14

I need to know the exact point location in my window where the caret currently resides so that I can pop up a small window under the text (similar to intellisense or a spell

相关标签:
7条回答
  • 2021-01-12 09:20

    Attach the following code snippet in the TextBox.KeyDown event to locate the screen point of the cursor within the text box control:

    using (Graphics g = Graphics.FromHwnd(textBox1.Handle))
    {
        SizeF size = g.MeasureString(textBox1.Text.Substring(0, textBox1.SelectionStart), textBox1.Font);
    
    Point pt = textBox1.PointToScreen(new Point((int)size.Width, (int)0));
        label1.Text = "Manual: " + pt.ToString();
    }
    

    The code snippet above takes into account the font used by the TextBox control to correctly calculate the actual length of the string up to the cursor position within the control. When performing an "Intellisense" style of auto complete popup, it's important to know the actual screen position in order to popup the "Auto completion" list.

    That's what the snippet does. It calculates the width of the text, then converts that with into a "local" coordinate to the TextBox control and from there converts that point into a relevant screen coordinate.

    One caveat to consider: the SelectionStart is delayed and not immediately updated. This is due in part to how the text box control handles keyboard input.

    0 讨论(0)
提交回复
热议问题