[英]c# GUI freezes after launching console application
我制作了一个运行 ping 并在文本字段中显示结果的应用程序。 当我单击开始 ping 按钮时,GUI 挂起并且没有任何内容输出到文本字段。 这个 GUI 挂起的原因是可以理解的,GUI 正在等待控制台应用程序完成。 我不明白如何在控制台应用程序的文本字段中实现输出。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApp4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Class1 ping = new Class1();
ping.startPing();
string output = ping.output();
richTextBox1.AppendText(output + "\n");
richTextBox1.Update();
}
static private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
}
class Class1
{
private Process p = new Process();
public void startPing()
{
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "c:/windows/system32/ping";
p.StartInfo.Arguments = "8.8.8.8 -t";
p.Start();
}
public string output()
{
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}
}
}
此代码将有助于解决您的查询。
private void button1_Click(object sender, EventArgs e)
{
var worker = new BackgroundWorker();
worker.DoWork += (o, ea) =>
{
Class1 ping = new Class1();
ping.startPing();
string output = ping.output();
richTextBox1.AppendText(output + "\n");
richTextBox1.Update();
};
worker.RunWorkerCompleted += (o, ea) =>
{
//You will get pointer when this worker finished the job.
};
worker.RunWorkerAsync();
}
如果在使用您的来源实施后有任何问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.