2017-01-25 39 views
1

在我的代碼下載事件我有這樣兩條線:如何更改richTextBox行文本的一部分?

RichTextBoxExtensions.AppendText(richTextBox1, "Downloading: ", Color.Red); 
RichTextBoxExtensions.AppendText(richTextBox1, url, Color.Green); 

代碼的一部分

int count = 0; 
     private void DownloadFile() 
     { 
      if (_downloadUrls.Any()) 
      { 
       WebClient client = new WebClient(); 
       client.DownloadProgressChanged += client_DownloadProgressChanged; 
       client.DownloadFileCompleted += client_DownloadFileCompleted; 

       var url = _downloadUrls.Dequeue(); 

       client.DownloadFileAsync(new Uri(url), @"C:\Temp\New folder (13)\" + count + ".txt"); 
       RichTextBoxExtensions.AppendText(richTextBox1, "Downloading: ", Color.Red); 
       RichTextBoxExtensions.AppendText(richTextBox1, url, Color.Green); 
       richTextBox1.AppendText(Environment.NewLine); 
       count++; 
       countCompleted--; 
       label1.Text = countCompleted.ToString(); 
       return; 
      } 

      // End of the download 
      btnStart.Text = "Download Complete"; 
     } 

     private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) 
     { 
      if (e.Error != null) 
      { 
       // handle error scenario 
       throw e.Error; 
      } 
      else 
      { 

      } 
      if (e.Cancelled) 
      { 
       // handle cancelled scenario 
      } 
      DownloadFile(); 
     } 

什麼我想要做的每一次文件下載完成這是在完成事件是將部分「Downloading:」更改爲「Downloaded:」和整行。

類RichTextBoxExtensions

public class RichTextBoxExtensions 
     { 
      public static void AppendText(RichTextBox box, string text, Color color) 
      { 
       box.SelectionStart = box.TextLength; 
       box.SelectionLength = 0; 

       box.SelectionColor = color; 
       box.AppendText(text); 
       box.SelectionColor = box.ForeColor; 
      } 
     } 

回答

0

這裏是你問:

public static class RichTextBoxExtensions 
{ 
    public static void AppendText(this RichTextBox box, string text, Color color) 
    { 
     box.SelectionStart = box.TextLength; 
     box.SelectionLength = 0; 

     box.SelectionColor = color; 
     box.AppendText(text); 
     box.SelectionColor = box.ForeColor; 
    } 
    public static void UpdateText(this RichTextBox box, string find, string replace, Color? color) 
    { 
     box.SelectionStart = box.Find(find, RichTextBoxFinds.Reverse); 
     box.SelectionLength = find.Length; 
     box.SelectionColor = color ?? box.SelectionColor; 
     box.SelectedText = replace; 
    } 
} 

我還糾正了擴展方法,這樣你就可以直接調用它們:

richTextBox1.AppendText("Downloading: ", Color.Red); 
richTextBox1.AppendText("qwe", Color.Green); 

// ... 

richTextBox1.UpdateText("Downloading: ", "Downloaded: ", Color.Green); 
相關問題