TextBox 光标位置





5.00/5 (4投票s)
获取 TextBox 中的行号和光标位置
我正在使用一个多行
System.Windows.Forms.TextBox
来开发一个简单的编辑器。我不知道如何获取光标位置,所以在网上搜索后找到了(某个地方)textbox.GetLineFromCharIndex ( textbox.SelectionStart )
用于获取行号,textbox.SelectionStart - textbox.GetFirstCharIndexOfCurrentLine
用于获取行内的位置。它们似乎工作正常,直到我注意到当我选择一些文本时,行内位置得到了一些负值。经过一些实验和探索,我放弃了使用 GetFirstCharIndexOfCurrentLine
* 方法,转而使用 GetFirstCharIndexFromLine
方法。现在我通过这种方式获取光标位置public static partial class LibExt
{
public static System.Drawing.Point
CurrentCharacterPosition
(
this System.Windows.Forms.TextBox TextBox
)
{
int s = TextBox.SelectionStart ;
int y = TextBox.GetLineFromCharIndex ( s ) ;
int x = s - TextBox.GetFirstCharIndexFromLine ( y ) ;
return ( new System.Drawing.Point ( x , y ) ) ;
}
}
* 看起来 GetFirstCharIndexOfCurrentLine
使用光标的位置来确定哪个行是“current
”,而我们试图使用 SelectionStart
位置。