简体   繁体   English

C#在文本框中的光标位置插入char

[英]C# Insert char at cursor position in textbox

I know there are some answers on stackoverflow but when I try it it inserts the text at the begin of text... 我知道有一些关于stackoverflow的答案,但是当我尝试它时,它将在文本的开头插入文本...

I tried 我试过了

string insertText = "$";
int selectionIndex = textBox1.SelectionStart;
textBox1.Text = textBox1.Text.Insert( selectionIndex, insertText );

I don't know exactly in what context you are using it, but for me (.NET 4.6.1) this code works fine if used in a button handler, but only after the first click. 我不确切知道您在什么上下文中使用它,但是对我来说(.NET 4.6.1)如果在按钮处理程序中使用,则此代码可以正常工作,但只能在第一次单击后使用。 Changing the text in the TextBox seems to reset the cursor position. 更改文本TextBox似乎会重置光标位置。

So to keep the cursor at its original place you have to set it back to what it was before you inserted the new text: 因此,要将光标保持在其原始位置,您必须将其设置回插入新文本之前的位置:

string insertText = "$";
int selectionIndex = textBox1.SelectionStart;
textBox1.Text = textBox1.Text.Insert( selectionIndex, insertText );
textBox1.SelectionStart = selectionIndex; // restore cursor position

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM