TextBox 光标位置





5.00/5 (1投票)
好的,这里还有另一种方法(我在 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 ;}[ ...
好的,这里还有另一种方法(我在 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 ) ) ;
}
这会获取光标的像素位置。但是你无法指定哪个控件,所以我假设它使用拥有焦点的控件。一旦你获得了像素位置,就可以使用 GetCharIndexFromPosition
来获取最近字符的索引。但是... 当光标位于文本末尾时,索引将指示前一个字符,而不是下一个字符将要插入的位置,因此它不如使用 SelectionStart
那么准确。