我有一个标准的WinForms文本框,我想在光标位置插入文本。如何获取光标位置?
谢谢。
不论文本是否被选中,SelectionStart 属性都代表插入符在文本中的索引位置。因此您可以使用 String.Insert 方法来添加一些文本,比如这样:
myTextBox.Text = myTextBox.Text.Insert(myTextBox.SelectionStart, "Hello world");
SelectionStart
属性。詹姆斯,当你只想在光标位置插入一些文本时,替换整个字符串非常低效。
更好的解决方案是:
textBoxSt1.SelectedText = ComboBoxWildCard.SelectedItem.ToString();
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;
}
}
您需要将 SelectionStart
属性存储在一个变量中,然后当您按下按钮时,将焦点移回到文本框。然后将 SelectionStart
属性设置为变量中的属性。
TextBox
文本内单击鼠标时插入符号的位置,请使用TextBox
的MouseDown
事件。使用MouseEventArgs
的X和Y属性创建一个点。TextBox
有一个名为GetCharIndexFromPosition(point)
的方法,将该点传递给它并返回插入符号的位置。如果您使用鼠标确定要插入新文本的位置,则此方法可行。请注意保留HTML标签。您建议我在什么事件中记录变量?是离开吗?
目前我有:
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());
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