Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

TextBox cursor position

0.00/5 (No votes)
25 Dec 2011 1  
OK, here's another way (I found this at http://dotnet.mvps.org/dotnet/faqs/?id=textboxcaretpos&lang=en[^]). [System.Runtime.InteropServices.StructLayoutAttribute (System.Runtime.InteropServices.LayoutKind.Sequential)]private struct ApiXY{ public int X ; public int Y ;}[ ...
OK, here's another way (I found this at http://dotnet.mvps.org/dotnet/faqs/?id=textboxcaretpos&lang=en[^]).

[System.Runtime.InteropServices.StructLayoutAttribute
  (System.Runtime.InteropServices.LayoutKind.Sequential)]
private struct ApiXY
{
  public int X ;
  public int Y ;
}

[
    System.Runtime.InteropServices.DllImportAttribute
    (
        "User32"
    ,
        SetLastError=true
    ,
        EntryPoint="GetCaretPos"
    )
]
private static extern bool
API_GetCaretPos ( ref ApiXY xy ) ;

public static System.Drawing.Point
GetCaretPos
(
)
{
    ApiXY xy = new ApiXY() ;

    API_GetCaretPos ( ref xy ) ;

    return ( new System.Drawing.Point ( xy.X , xy.Y ) ) ;
}


This gets the pixel position of the caret. But you can't specify which Control, so I assume it uses the Control with the focus.
Once you have the pixel position, you can use GetCharIndexFromPosition to get the index of the nearest character. Buuut... when the caret is at the end of the text, the index will indicate the previous character rather than where the next character will go, so it's kinda sorta less accurate than using SelectionStart.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here