winforms C#从Windows窗体接收控制台writeline到richtextbox中

bnl4lu3b  于 2022-12-14  发布在  C#
关注(0)|答案(1)|浏览(165)

我看过所有类似的问题。我似乎不明白为什么我的情况不起作用。我用下面的类创建了一个测试应用程序:

public class TextBoxStreamWriter : TextWriter
{
    RichTextBox _output = null;

    public TextBoxStreamWriter(RichTextBox output)
    {
        _output = output;
    }

    public override void Write(char value)
    {
        base.Write(value);
        _output.AppendText(value.ToString()); // When character data is written, append it to the text box.
    }

    public override Encoding Encoding
    {
        get { return System.Text.Encoding.UTF8; }
    }}

我的表单代码

public partial class Form1 : Form
{
   
    TextWriter _writer = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        _writer = new TextBoxStreamWriter(richTextBox1);

        // Redirect the out Console stream
        Console.SetOut(_writer);

        //Console.WriteLine("Now redirecting output to the text box");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Writing to the Console now causes the text to be displayed in the text box.
        Console.WriteLine("Hello world");
    }

}

我每次点击按钮都能正常工作。现在我的问题是为什么它在那里工作而在我的项目中不工作。我用API 3创建了一个Youtube上传应用程序,它上传完成了,但控制台的writeline显示了消息,而我的richtextbox只显示了我最初的视频上传消息。我只想捕获写的几个原因显示任何错误,调用控制台时获取progressbar的progress并获取video.ID。writeline我的richtextbox没有更新这里是正在使用的代码

/// <summary>
    /// Upload video to youtube
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button2_Click(object sender, EventArgs e)
    {
        //lblstatus.Text = "uploading video";
        Console.WriteLine("uploading video");
        try
        {
            Thread thead = new Thread(() =>
            {
                Run().Wait();
            });
            thead.IsBackground = true;
            thead.Start();

        }
        catch (AggregateException ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            // MessageBox.Show(ex.Message);
        }
    }

    private async Task Run()
    {
        UserCredential credential;
        using (var stream = new FileStream("client_secret", FileMode.Open, FileAccess.Read))
        {
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.FromStream(stream).Secrets,
                // This OAuth 2.0 access scope allows an application to upload files to the
                // authenticated user's YouTube channel, but doesn't allow other types of access.
                new[] { YouTubeService.Scope.YoutubeUpload },
                "user",
                CancellationToken.None
            );
        }

        var youtubeService = new YouTubeService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
        });

        var video = new Video();
        video.Snippet = new VideoSnippet();
        video.Snippet.Title = txtTitle.Text;
        video.Snippet.Description = txtDescription.Text;
        string[] tagSeo = Regex.Split(txtTagSeo.Text, ","); 
        video.Snippet.Tags = tagSeo;
        video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
        video.Status = new VideoStatus();
        video.Status.PrivacyStatus = "public"; // or "private" or "public"
        var filePath = txtPath.Text; // Replace with path to actual movie file.

        Console.WriteLine(filePath);

        using (var fileStream = new FileStream(filePath, FileMode.Open))
        {
            var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
            videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
            videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

            await videosInsertRequest.UploadAsync();
        }
    }

    void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
    {
        switch (progress.Status)
        {
            case UploadStatus.Uploading:
                Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                //lblstatus.Text = String.Format("{0} bytes sent.", progress.BytesSent);
                break;

            case UploadStatus.Failed:
                //lblstatus.Text = String.Format("An error prevented the upload from completing.{0} ", progress.Exception);
                Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                break;
        }
    }

    void videosInsertRequest_ResponseReceived(Video video)
    {
        Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        MessageBox.Show("Video id '{0}' was successfully uploaded.", video.Id);
    }
c8ib6hqw

c8ib6hqw1#

我无法使上面的代码工作,所以我去了计划B。我开始获得视频ID,因为我每天只有6次尝试,我选择使用视频ID作为字符串。我删除了TextBoxStreamWriter类,并创建了一个新的线程和委托。我将工作在进度条值下。下面是我如何为其他可能有类似问题的人做的。创建了一个代理来更新我的视频ID标签,如下所示

public delegate void LabelDelegate(string s);

    void UpdateVideoID(string text)
    {
        if (lblVideoID.InvokeRequired)
        {
            LabelDelegate LDEL = new LabelDelegate(UpdateVideoID);
            lblVideoID.Invoke(LDEL, text);
        }
        else
            lblVideoID.Text = text;
    }

 void videosInsertRequest_ResponseReceived(Video video)
    {
        Thread th = new Thread(() => UpdateVideoID(video.Id));
        th.Start();
        Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);

    }

相关问题