Solve color problem in richtextbox in C#

Asked

Viewed 95 times

0

How do I click on button1 the text of richTextBox2 become a certain color, and I click on button2 text from the vertical input bar | become the color of the button2, my code below makes the color change of the entire text. I would like your help, thanks in advance!

Code:

   {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox2.ForeColor = Color.Green;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            richTextBox2.ForeColor = Color.Red;

        }


        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {
            richTextBox2.Text = richTextBox1.Text;
        }
    }
}

1 answer

0

If it’s something simple like just looking for a character and modifying the color from it, da para você fazer algo como:

int inicio = richTextBox2.Text.IndexOf('|');
if(inicio >= 0)
{
    richTextBox2.SelectionStart = inicio;
    richTextBox2.SelectionLength = richTextBox2.Text.Length - inicio;
    richTextBox2.SelectionColor = Color.Red;
}
  • what happens @Christian Beregula , in the code I use, I can’t leave two colors at the same time, or the text is whole red, or interim green, I believe what you demonstrated above would be a kind of replace

  • @Petrukio did not understand well what stops you from leaving the text with two colors at the same time. In the example above he will take the | up to the end of the text the color red, but nothing prevents you from controlling how far you need to go that color red by changing the SelectionLenght.

  • did I do wrong? I put the @Christian code like this see the image (http://i.imgur.com/5QzBTKA.png)

  • Your goal is just to split the text in two colors? What text are you using that is not working code? I printed the value of inicio, what value returns?

  • Did this answer solve your @Petrukio problem? If not, I have an extension method that can help you.

  • @jbueno function after changing some parts, but all knowledge is valid, if you can contribute, since grateful. my this now (http://i.imgur.com/55igCtP.png)

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.