将Console.WriteLine转换为文本框

时间:2011-03-07 14:47:54

标签: c# vb.net

Console.WriteLine("Network adapter: {0}", adapters[i].Name);
                Console.WriteLine("    Status:            {0}", adapters[i].OperationalStatus.ToString());
                Console.WriteLine("    Interface:         {0}", adapters[i].NetworkInterfaceType.ToString());
                Console.WriteLine("    Description:       {0}", adapters[i].Description);
                Console.WriteLine("    ID:                {0}", adapters[i].Id);
                Console.WriteLine("    Speed:             {0}", adapters[i].Speed);
                Console.WriteLine("    SupportsMulticast: {0}", adapters[i].SupportsMulticast);
                Console.WriteLine("    IsReceiveOnly:     {0}", adapters[i].IsReceiveOnly);
                Console.WriteLine("    MAC:               {0}", adapters[i].GetPhysicalAddress().ToString());

我想要的是将此Console.WriteLine显示在表单上的文本框中,但不知道如何操作。

4 个答案:

答案 0 :(得分:4)

如果像我一样你不喜欢StringBuilder解决方案,请查看Sébastien的博客

How to redirect the Console’s output to a TextBox in C#

答案 1 :(得分:3)

只需确保文本框设置为多行:

StringBuilder sb = new StringBuilder();

sb.AppendLine(string.Format("Network adapter: {0}", adapters[i].Name));
sb.AppendLine(string.Format("    Status:            {0}", adapters[i].OperationalStatus.ToString()));
sb.AppendLine(string.Format("    Interface:         {0}", adapters[i].NetworkInterfaceType.ToString()));
sb.AppendLine(string.Format("    Description:       {0}", adapters[i].Description));
sb.AppendLine(string.Format("    ID:                {0}", adapters[i].Id));
sb.AppendLine(string.Format("    Speed:             {0}", adapters[i].Speed));
sb.AppendLine(string.Format("    SupportsMulticast: {0}", adapters[i].SupportsMulticast));
sb.AppendLine(string.Format("    IsReceiveOnly:     {0}", adapters[i].IsReceiveOnly));
sb.AppendLine(string.Format("    MAC:               {0}", adapters[i].GetPhysicalAddress().ToString()));

textBox1.Text = sb.ToString();

答案 2 :(得分:0)

您可以尝试从此处阅读当前流程“stdout”:      System.Diagnostics.Process.GetCurrentProcess().StandardOutput

答案 3 :(得分:0)

如果您希望将现有的控制台应用程序传输到TextBox,这里有类似的内容,我将内容从进程传输到控制台。 http://www.bryancook.net/2008/03/redirect-standard-output-of-service-to.html

该示例与您要执行的操作之间的区别在于更改日志记录以将数据推送到文本框中。

但要注意!您只能从创建它的线程(UI线程)将输出附加到TextBox。您需要将来自其他线程的数据封送到UI线程。

See this answer有一个很棒的扩展方法可以将数据推送到用户界面。

你最终得到:

private static void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    if (!String.IsNullOrEmpty(e.Data))
    {
       _textBox.InvokeIfRequired( c => c.Text += e.Data );       
    }
}