64

我有一个标准的 WinForms TextBox,我想在文本中光标的位置插入文本。如何获取光标的位置?

谢谢

4

9 回答 9

93

无论是否选择了任何文本,SelectionStart属性都表示插入符号所在文本的索引。因此,您可以使用String.Insert注入一些文本,如下所示:

myTextBox.Text = myTextBox.Text.Insert(myTextBox.SelectionStart, "Hello world");
于 2009-02-08T22:38:19.380 回答
15

您想检查SelectionStart.TextBox

于 2009-02-08T22:36:14.660 回答
7

詹姆斯,当您只想在光标位置插入一些文本时,需要替换整个字符串是非常低效的。

更好的解决方案是:

textBoxSt1.SelectedText = ComboBoxWildCard.SelectedItem.ToString();

当您没有选择任何内容时,它将在光标位置插入新文本。如果您选择了某些内容,这会将您选择的文本替换为您要插入的文本。

我从eggheadcafe 网站找到了这个解决方案。

于 2009-04-16T23:10:20.457 回答
5

您所要做的就是:

双击将文本插入到光标处的文档的项目(按钮、标签等)。然后输入:

richTextBox.SelectedText = "whatevertextyouwantinserted";
于 2011-09-05T13:54:56.107 回答
4

这是我的工作实现,允许只输入数字,并恢复最后一个有效的输入文本位置:

xml:

<TextBox
      Name="myTextBox" 
      TextChanged="OnMyTextBoxTyping" />

后面的代码:

private void OnMyTextBoxTyping(object sender, EventArgs e)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(myTextBox.Text, @"^[0-9]+$"))
    {
        var currentPosition = myTextBox.SelectionStart;
        myTextBox.Text = new string(myTextBox.Text.Where(c => (char.IsDigit(c))).ToArray());
        myTextBox.SelectionStart = currentPosition > 0 ? currentPosition - 1 : currentPosition;
    }
}
于 2014-09-25T04:53:52.553 回答
2

您必须将SelectionStart属性保存在变量中,然后当您按下按钮时,将焦点移回 TextBox。然后将SelectionStart属性设置为变量中的那个。

于 2009-02-08T22:56:12.503 回答
2

你会建议我在什么情况下记录变量?离开?

目前我有:

private void comboBoxWildCard_SelectedIndexChanged(object sender, EventArgs e)
{
    textBoxSt1.Focus();
    textBoxSt1.Text.Insert(intCursorPos, comboBoxWildCard.SelectedItem.ToString());

}

private void textBoxSt1_Leave(object sender, EventArgs e)
{
    intCursorPos = textBoxSt1.SelectionStart;
}

正在录制离开事件,但没有插入文本,我错过了什么吗?

更新:我需要 textBoxSt1.Text =

textBoxSt1.Text = textBoxSt1.Text.Insert(intCursorPos, comboBoxWildCard.SelectedItem.ToString());

谢谢大家。

谢谢

于 2009-02-08T22:58:52.390 回答
1
int cursorPosition = textBox1.SelectionStart;
//it will extract your current cursor position where ever it is
//textBox1 is name of your text box. you can use one
//which is being used by you in your form
于 2013-04-09T09:37:47.853 回答
1

要在 a 的文本中单击鼠标时获取插入符号的位置,请TextBox使用TextBox MouseDown事件。使用 的 X 和 Y 属性创建一个点MouseEventArgs。有TextBox一个方法叫做GetCharIndexFromPosition(point). 将点传递给它,它会返回插入符号的位置。如果您使用鼠标来确定要插入新文本的位置,则此方法有效。

于 2014-05-19T00:19:49.137 回答