65.9K
CodeProject is changing. Read more.
Home

TextBox cursor position

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Dec 6, 2011

CPOL
viewsIcon

9072

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.