如何更改richTextBox行文本的一部分?

时间:2017-01-25 21:57:53

标签: c# .net winforms

在我的代码的下载事件中,我有两行:

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();
        }

我想要做的是每次文件下载完成后,在完成的事件中更改部分"下载:"到"已下载:"和整条线。

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;
            }
        }

1 个答案:

答案 0 :(得分: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);