我制作了一个运行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;
}
}
}
答案 0 :(得分:-3)
此代码将有助于解决您的查询。
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();
}
让我知道在用源实现它之后是否有任何问题。