Hello. I'm doing a html editor.
i want a function to the html editor that change the color on the text when I press a button. Example if I write this code in the html editors textbox:
<table><tr><td bgcolor = "abc123">hello</td></tr><table>
And then I press the button would it change the text color like this:
<table><tr><td bgcolor = "abc123">hello</td></tr></table>
What code should I use for that function?

Recommended Answers

All 12 Replies

Hi, Use RichTextBox for editor. This control has SelectionColor property to change the color of the Selected Text.

But selecting should be done by you

But i want it to change the color by it self. And when i press the button would the text color change and I want it to change all the letters color inside <>.

Rich Text Box has KeyDown Event where you have to change the color by ur code when receiving '<' and '>' characters. This change the color when typing

If you want to set the color when press a button, then parse the text first, then apply the color to the text

could you make the code for me?

I also need the code for this..?

Anyone know how to do it?

Yes, I give simple example

private char LastChar = ' ';
    private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        if (LastChar == '<')
            //Turn On Red after Pressing < character
            richTextBox1.SelectionColor = Color.Red; 
        if (e.KeyChar == '>')
            //Turn Off Red Color
            richTextBox1.SelectionColor = richTextBox1.ForeColor;
        LastChar = e.KeyChar;

Hmm... That won't work well. We need to use Regular expressions. Anyone familiar with it?

The above code that i posted only works when type the tags

When you want change the color by pressing button. I am not familiar with Regular Expression, still a try.
Try this

private void button1_Click(object sender, EventArgs e)
        Regex regex = new Regex(@"(<\b[^>]*>)|(</\b[^>]*>)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        for (Match match = regex.Match(richTextBox1.Text ); match.Success; match = match.NextMatch())
            richTextBox1.Select ( match.Index +1, match.Value.Length -2);
            richTextBox1.SelectionColor = Color.Red ;
            richTextBox1.DeselectAll ();
commented: Thanks man. You solved our problem! - farooqaaa +1

It didn't work for me, I've got five errors.

Now I got it to work I require this line of code to:
using System.Text.RegularExpressions;

Thanks a million salva. I got it working finally.

@FullBjarne: I didn't saw Page 2. I was going to tell you to use that. :)

Thanks again salva. :)

I wonder how to make this fire a certain intervals, for example on the press of the space bar, or something. hrm.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.