How do I change the forground color of selected text?

With a KeyUp event in txtInput (text box), I want to see if it finds html commands and highlight them with a blue color. Right now, it's highlighting everything in the textbox if it finds a html tag. How can I make sure it only sets the color of one word

Phil

private void txtInput_KeyUp(object sender, KeyEventArgs e)

{

string code = "<html>";

if (txtInput.Find(code) != -1)

{

txtInput.ForeColor = Color.Blue;

// txtInput.SelectedText.ForeColor = Color.Blue;   // wrong, but an ideal approach

}

else

{

}

}



Answer this question

How do I change the forground color of selected text?

  • LisaF

    Here's an update of my code: I'm getting a ton of repeated letters in the textbox, though. What do you think I can improve on here My resource is from this site:  http://www.c-sharpcorner.com/Code/2003/June/SyntaxHighlightInRichTextBoxP1.asp

    private void txtInput_KeyUp(object sender, KeyEventArgs e)

    {

    char[] t = { '(', '[', ' ', '\t', '{', '}', '(', ')', ':', ';', ']' };

    String[] tokens = txtInput.Text.Split(t);

    foreach (string token in tokens)

    {

    txtInput.SelectionColor = Color.Black;

    txtInput.SelectionFont = new Font("Courier New", 10, FontStyle.Regular);

    // Check whether the token is a keyword.

    String[] keywords = {"public", "void", "using", "static", "class"};

    for (int i = 0; i < keywords.Length; i++)

    {

    if (keywordsIdea == token)

    {

    // Apply alternative color

    txtInput.SelectionColor = Color.Blue;

    txtInput.SelectionFont = new Font("Courier New", 10, FontStyle.Bold);

    break;

    }

    }

    txtInput.SelectedText = token;

    //txtInput.SelectedText = "\n";

    }

    }


  • How do I change the forground color of selected text?