如何在Richtextbox的每一行的开头添加字符 [英] how to add a character at the beginning of each line in Richtextbox
本文介绍了如何在Richtextbox的每一行的开头添加字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一个应用程序,如果您单击该按钮,则会为每个选定的行添加一个特定的字符.例如在Richtextbox的每一行中将"//"都涂成红色,就像在Visual Studio中注释掉功能一样
I am doing an app that adds a certain character for each selected line if you click the button. for example "//" in each line in a Richtextbox and colored the text into red, it is like the function of comment out in visual studio
我尝试了这个,但是没有用
i tried this but it did'nt work
private void toolStripButton1_Click(object sender, EventArgs e)
{
int firstCharPosition = richTextBox1.GetFirstCharIndexOfCurrentLine();
int lineNumber = richTextBox1.GetLineFromCharIndex(firstCharPosition);
int lastCharPosition = richTextBox1.GetFirstCharIndexFromLine(lineNumber + 1);
if (richTextBox1.SelectionLength > 0)
{
richTextBox1.SelectionColor = Color.Red;
richTextBox1.SelectedText = "//" + richTextBox1.SelectedText.ToString();
}
else
{
richTextBox1.Select(firstCharPosition, lastCharPosition - firstCharPosition);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.SelectedText = "//" + richTextBox1.SelectedText.ToString();
}
}
伙计们请帮我谢谢!
推荐答案
if (richTextBox1.Text.Length > 0 && richTextBox1.SelectionLength >= 0)
{
string[] lines = richTextBox1.Text.Split(new string[] { Environment.NewLine, "\n", "\r", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
Color normalColor = Color.Black, commentColor = Color.Red;
int selStart = richTextBox1.SelectionStart, selEnd = selStart + richTextBox1.SelectionLength,
startLine = -1, endLine = -1, lineSum = 0, k = 0;
for (k = 0; k < lines.Length; k++)
if (startLine == -1)
{
if ((lineSum += lines[k].Length + 1) > selStart)
{
startLine = k;
if (selEnd <= lineSum) endLine = k;
}
}
else if (endLine == -1)
{
if ((lineSum += lines[k].Length + 1) >= selEnd)
endLine = k;
}
else break;
for (int i = 0; i < lines.Length; i++)
lines[i] = (i >= startLine && i <= endLine ? "//" : "") + lines[i];
richTextBox1.Text = "";
richTextBox1.SelectionStart = 0;
for (int i = 0; i < lines.Length; i++)
{
richTextBox1.SelectionStart = richTextBox1.Text.Length;
richTextBox1.SelectionColor = lines[i].TrimStart().StartsWith("//") ? commentColor : normalColor;
richTextBox1.SelectedText = lines[i] += (i == lines.Length - 1 ? "" : "\r\n");
}
int selectStarIndx = richTextBox1.GetFirstCharIndexFromLine(startLine), selectEndIndx = richTextBox1.GetFirstCharIndexFromLine(endLine + 1);
if (selectEndIndx == -1) selectEndIndx = richTextBox1.Text.Length;
richTextBox1.Select(selectStarIndx, selectEndIndx - selectStarIndx);
richTextBox1.Focus();
}
这篇关于如何在Richtextbox的每一行的开头添加字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文