将文本行粘贴到文本框中的光标处
所以我正在开发一个基本的记事本程序,旨在对网页设计师有所帮助。我有一个可以粘贴到编辑器中的不同代码块的列表,但我无法按照我想要的方式粘贴它们。基本上,我希望能够在文本编辑器上的两行(或单词,无论何处)之间单击,并能够将这些块粘贴到闪烁光标所在的位置。
这是我当前选择其中一个粘贴选项时的代码:
public void getCodeBlock(string selection)
{
string[] codeBlocks = System.IO.File.ReadAllLines(@"blocks\" + selection + ".txt");
foreach (string codeBlock in codeBlocks)
{
int cursorPosition = richTextBox1.SelectionStart;
string insertText = codeBlock + Environment.NewLine;
richTextBox1.Text = richTextBox1.Text.Insert(cursorPosition, insertText);
cursorPosition = cursorPosition + insertText.Length;
}
}
但是,它不是将其粘贴到光标处,而是完全混乱了行,有时甚至从最后一行粘贴到第一行。我完全不知道我做错了什么,并且确实需要一些帮助。
so I'm working on a basic notepad program designed to be helpful toward web designers. I have a list of different blocks of code that can be pasted into the editor, but I'm having trouble pasting them how I want it. Basically, I'd like to be able to click between two lines (or words, whereever) on the text editor, and be able to paste these blocks where the blinking cursor would be.
Here's my current code for when one of the pasting options is selected:
public void getCodeBlock(string selection)
{
string[] codeBlocks = System.IO.File.ReadAllLines(@"blocks\" + selection + ".txt");
foreach (string codeBlock in codeBlocks)
{
int cursorPosition = richTextBox1.SelectionStart;
string insertText = codeBlock + Environment.NewLine;
richTextBox1.Text = richTextBox1.Text.Insert(cursorPosition, insertText);
cursorPosition = cursorPosition + insertText.Length;
}
}
However, instead of pasting it at the cursor, it completely jumbles up the lines, and sometimes even pastes it from the last line to the first. I have absolutely no idea what I'm doing wrong, and could really use some help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正是这一行导致了问题:
请尝试以下操作:
当您更改
richTextBox1
的Text
属性时,选择位置将重置为 0。cursorPosition
是局部变量,下次循环时它将采用新值。It's this line that is causing the problem:
Try this instead:
The selection position gets reset to 0 when you change the
Text
property of therichTextBox1
.cursorPosition
is your local variable which then takes on the new value the next time through the loop.我真的不明白你的代码应该做什么。
我没有太多使用 RichTextBox,但是,如果您想在当前位置插入一些文本,只需执行
richTextBox1.SelectedText = insertText
即可。 (请注意,这将替换选定的文本(如果有)。)您可以使用
richTextBox1.SelectionStart
和richTextBox1.SelectionLength
来更改当前位置/选择。I really can't figure out what your code is supposed to do.
I haven't worked much with RichTextBox but, if you want to insert some text at the current position, just do
richTextBox1.SelectedText = insertText
. (Note that this will replace selected text, if any.)You can use
richTextBox1.SelectionStart
andrichTextBox1.SelectionLength
to alter the current position/selection.