简体   繁体   中英

Selecting specific line on richtextbox

How would I make it so that when a user types in '{' into a richtextbox it will select the next line for them ? For example,

private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        if (richTextBox1.Text.Contains("{"))
        {
            richTextBox1.AppendText(Environment.NewLine + "    "); // line 1
            // Put user on line 1
            richTextBox1.AppendText(Environment.NewLine + "}"); // line 2
        }
    }

You can do this by getting the length of the text box before adding the second line, and then selecting 0 characters at the end of it after adding the second line.

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    if (richTextBox1.Text.Contains("{"))
    {
        richTextBox1.AppendText(Environment.NewLine + "    "); // line 1
        int lastIndex = richTextBox1.Text.Length - 1;
        richTextBox1.AppendText(Environment.NewLine + "}"); // line 2
        richTextBox1.SelectionStart = lastIndex;
        richTextBox1.SelectionLength = 0;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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