gpt4 book ai didi

c# - 如何在Richtextbox的每一行的开头添加一个字符

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:39 24 4
gpt4 key购买 nike

我正在做一个应用程序,如果您单击按钮,它会为每个选定的行添加一个特定的字符。比如Richtextbox中每一行的"//",然后将文本着色成红色,就像visual studio中的注释功能

我试过了,但是没用

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();
}

关于c# - 如何在Richtextbox的每一行的开头添加一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28871381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com