2017-05-06 8 views
0
string words; 
    private void Colors(object sender, EventArgs e) 
    { 
     Color tags = new Color(); 
     tags = Color.FromArgb(33, 66, 99); 
    } 
    private Color FromRgbExample() 
    { 
     // Create a green color using the FromRgb static method. 
     Color myRgbColor = new Color(); 
     myRgbColor = Color.FromArgb(0, 255, 0); 
     return myRgbColor; 
    } 
    private void CheckKeyword(string word, Color color, int startIndex) 
    { 
     words = word; 
     if (this.richTextBox1.Text.Contains(word)) 
     { 
      int index = -1; 
      int selectStart = this.richTextBox1.SelectionStart; 

      while ((index = this.richTextBox1.Text.IndexOf(word, (index + 1))) != -1) 
      { 

       this.richTextBox1.Select((index + startIndex), word.Length); 
       this.richTextBox1.SelectionColor = color; 
       this.richTextBox1.Select(selectStart, 0); 
       this.richTextBox1.SelectionColor = Color.Black; 
      } 
     } 
    } 
    private void richTextBox1_TextChanged(object sender, EventArgs e) 
    { 

     this.CheckKeyword("html", Color.Green, 0); 
     this.CheckKeyword("head", Color.Green, 0); 

     if (richTextBox1.Text.Contains(words) == false) 
     { 
      this.richTextBox1.SelectionColor = Color.Black; 
     } 
    } 


} 

Si j'écris "html" le texte aura la couleur verte, si je supprime une lettre de "html" il sera toujours avec la couleur verte. Comment puis-je faire après avoir supprimé une lettre pour changer la couleur "html" en noir?C# richbox changer la couleur

+0

Vous devrez refaire __all__ les vérifications et la coloration chaque fois que vous changez le texte. Cela signifie que tout est noir, puis re-colorez. Peut-être que vous pouvez optimiser mais comme un TextChanged peut être sur une seule lettre ou des paragraphes entiers insérer ou supprimer ce ne sera pas trivial .. – TaW

+0

Couleurs était juste un test, je veux savoir comment faire si (richTextBox1.Text.Contains (words) == false) { this.richTextBox1.SelectionColor = Couleur.Black; } –

+0

Eh bien, c'est ainsi que vous devez procéder, mais vous devez également sélectionner la partie du texte que vous voulez colorier. Mieux écrire une fonction qui trouve tous les mots-clés et les couleurs. [Voir ici] (http://stackoverflow.com/questions/26530443/how-do-you-search-for-a-string-in-a-rich-text-box-and-highlight-all-found-or -hig/26533012 # 26533012) pour un exemple .. – TaW

Répondre

0
private void richTextBox1_TextChanged(object sender, EventArgs e) 
{ 
    richTextBox1.Select(0,richTextBox1.Text.Length -1); 
    richTextBox1.SelectionColor = Color.Black; 
    richTextBox1.SelectionStart = 0; 

    this.CheckKeyword("html", Color.Green, 0); 
    this.CheckKeyword("head", Color.Green, 0); 

    if (richTextBox1.Text.Contains(words) == false) 
    { 
     this.richTextBox1.SelectionColor = Color.Black; 
    } 
}