这个应该很容易。
以下是一个例子:
用户单击标题为“Ping”的按钮,它使用命令提示符“ping”来ping服务器。输出以字符串形式捕获,并在Windows窗体应用程序中显示给用户。
答案 0 :(得分:5)
使用Process
类开始新进程。您可以重定向标准错误和输出 - 在这种情况下,您可能希望以事件驱动的方式执行此操作,以便在ping出来时将文本写入应用程序。
假设您希望用户看到输出,不想要在输出上使用ReadToEnd - 这将阻塞直到它完成。
这是一个写入控制台的完整示例 - 但它显示了如何在进程写入输出时执行此操作,而不是等待进程完成:
using System;
using System.Diagnostics;
class Test
{
static void Main(string[] args)
{
ProcessStartInfo psi = new ProcessStartInfo("ping")
{
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = "google.com"
};
Process proc = Process.Start(psi);
proc.EnableRaisingEvents = true;
proc.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
proc.BeginOutputReadLine();
proc.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
proc.BeginErrorReadLine();
proc.WaitForExit();
Console.WriteLine("Done");
}
}
这是一个完整的WinForms应用程序:
using System;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
class Test
{
[STAThread]
static void Main(string[] args)
{
Button button = new Button {
Text = "Click me",
Dock = DockStyle.Top
};
TextBox textBox = new TextBox {
Multiline = true,
ReadOnly = true,
Location = new Point(5, 50),
Dock = DockStyle.Fill
};
Form form = new Form {
Text = "Pinger",
Size = new Size(500, 300),
Controls = { textBox, button }
};
Action<string> appendLine = line => {
MethodInvoker invoker = () => textBox.AppendText(line + "\r\n");
textBox.BeginInvoke(invoker);
};
button.Click += delegate
{
ProcessStartInfo psi = new ProcessStartInfo("ping")
{
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = "google.com"
};
Process proc = Process.Start(psi);
proc.EnableRaisingEvents = true;
proc.OutputDataReceived += (s, e) => appendLine(e.Data);
proc.BeginOutputReadLine();
proc.ErrorDataReceived += (s, e) => appendLine(e.Data);
proc.BeginErrorReadLine();
proc.Exited += delegate { appendLine("Done"); };
};
Application.Run(form);
}
}
答案 1 :(得分:2)
Process p = System.Diagnostics.Process.Start("ping ....");
System.IO.StreamReader reader = p.StandardOutput;
string sRes = reader.ReadToEnd();
reader.Close();
字符串变量sRes
应包含ping
命令的结果。
答案 2 :(得分:1)
public static string Ping(string url)
{
Process p = System.Diagnostics.Process.Start("ping.exe", url);
StreamReader reader = p.StandardOutput;
String output = reader.ReadToEnd();
reader.Close();
return output;
}
答案 3 :(得分:0)
我在blog上广泛报道了这一点。您可以复制粘贴完全可编译的示例。只需要对Winforms有一个非常基本的了解,你就可以自己填写空白。