【发布时间】:2010-10-06 07:22:42
【问题描述】:
我有一个标准的 WinForms TextBox,我想在文本中光标的位置插入文本。如何获取光标的位置?
谢谢
【问题讨论】:
-
您需要在全屏还是表格中定位?
-
你能看我下面的最后一篇文章吗?谢谢
标签: c# cursor-position
我有一个标准的 WinForms TextBox,我想在文本中光标的位置插入文本。如何获取光标的位置?
谢谢
【问题讨论】:
标签: c# cursor-position
无论是否选择了任何文本,SelectionStart 属性都表示插入符号所在文本的索引。所以你可以使用String.Insert 来注入一些文本,像这样:
myTextBox.Text = myTextBox.Text.Insert(myTextBox.SelectionStart, "Hello world");
【讨论】:
您想检查TextBox 的SelectionStart 属性。
【讨论】:
James,当您只想在光标位置插入一些文本时,需要替换整个字符串是非常低效的。
更好的解决方案是:
textBoxSt1.SelectedText = ComboBoxWildCard.SelectedItem.ToString();
当您没有选择任何内容时,它将在光标位置插入新文本。 如果您选择了某些内容,这会将您选择的文本替换为您要插入的文本。
我从eggheadcafe site 找到了这个解决方案。
【讨论】:
你所要做的就是:
双击将文本插入文档中光标处的项目(按钮、标签等)。然后输入:
richTextBox.SelectedText = "whatevertextyouwantinserted";
【讨论】:
这是我的工作实现,允许只输入数字,并恢复上次有效的输入文本位置:
Xaml:
<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;
}
}
【讨论】:
你会建议我在什么事件上记录变量?离开?
目前我有:
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());
谢谢大家。
谢谢
【讨论】:
您必须将SelectionStart 属性保留在一个变量中,然后当您按下按钮时,将焦点移回TextBox。然后将SelectionStart 属性设置为变量中的那个。
【讨论】:
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
【讨论】:
要在TextBox 的文本中单击鼠标时获取插入符号的位置,请使用TextBox MouseDown 事件。使用MouseEventArgs 的 X 和 Y 属性创建一个点。 TextBox 有一个名为 GetCharIndexFromPosition(point) 的方法。将点传递给它,它会返回插入符号的位置。如果您使用鼠标来确定要插入新文本的位置,则此方法有效。
【讨论】: