如何获取.NET中winforms文本框的当前光标(插入符号)位置?SelectionStart仅返回所选文本的开始(所选内容的左侧)。表示如果光标位于所选内容的右侧,则此值是错误的。
需要说明的是:在.NET TextBox中,当插入标记位于选择的右侧时,SelectionStart也指向选择的左侧。这意味着在两张图片中SelectionStart均为2,但插入标记的位置在第一张图片中为2,在右边图片中为7。
如前所述,该SelectionStart属性对于在激活选择的情况下获取TextBox中的实际CARET位置并不可靠。这是由于以下事实导致的:此属性始终指向选择的开始(提示:名称不说谎),并且根据您用鼠标选择文本的方式,插入号可以位于选择的左侧或右侧。 。
这段代码(通过LinqPAD测试)显示了一种替代方法
public class WinApi
{
[DllImport("user32.dll")]
public static extern bool GetCaretPos(out System.Drawing.Point lpPoint);
}
TextBox t = new TextBox();
void Main()
{
Form f = new Form();
f.Controls.Add(t);
Button b = new Button();
b.Dock = DockStyle.Bottom;
b.Click += onClick;
f.Controls.Add(b);
f.ShowDialog();
}
// Define other methods and classes here
void onClick(object sender, EventArgs e)
{
Console.WriteLine("Start:" + t.SelectionStart + " len:" +t.SelectionLength);
Point p = new Point();
bool result = WinApi.GetCaretPos(out p);
Console.WriteLine(p);
int idx = t.GetCharIndexFromPosition(p);
Console.WriteLine(idx);
}
Run Code Online (Sandbox Code Playgroud)
API GetCaretPos返回客户端坐标中CARET所在的点。您可以使用托管方法返回位置后的字符索引GetCharIndexFromPosition。当然,您需要为添加一个参考和一个用法System.Runtime.InteropServices。
不确定此解决方案是否存在缺点,请耐心等待是否有其他专家可以告诉我们是否存在问题或无法解释。
| 归档时间: |
|
| 查看次数: |
4502 次 |
| 最近记录: |