2009-02-23 2 views
9

저는 Windows Forms를 처음 사용합니다. VS 2008, C#을 사용하여 RichTextBox를 작성하고 있습니다. RichTextBox에 쓸 때 각기 다른 색으로 채색 할 수 있기를 원합니다. 누군가 샘플을 가르쳐 줄 수 있습니까? 감사RichTextBox 색상이 선택되었습니다.

foreach (string file in myfiles) 
{ 
    // As I process my files 
    // richTextBox1.Text += "My processing results"; 
    if(file == "somefileName") 
    { 
    // Color above entered line or enter new colored line 
    } 

} 

답변

13

당신이 추가하기 전에 설정 SelectionColor, 같은 :

int line = 0; 
    foreach (string file in myfiles) 
    { 
     // Whatever method you want to choose a color, here 
     // I'm just alternating between red and blue 
     richTextBox1.SelectionColor = 
      line % 2 == 0 ? Color.Red : Color.Blue; 

     // AppendText is better than rtb.Text += ... 
     richTextBox1.AppendText(file + "\r\n"); 
     line++; 
    } 
+0

1. VB.Net 사용자는 C#에서 \ r \ n이 (가) 이스케이프하고 있음을 기억해야합니다. VB에서 AppendText (파일 및 vbCrLf) 쓰기. – smirkingman

+0

코드 주석에서 언급했듯이 + =를 사용하면 이미 상자에 설정된 텍스트 색상이 모두 재설정되어 AppendText 메서드가 트릭을 수행 한 것으로 보입니다. – kad81