您的位置:首页 > 编程语言 > C#

C#调用CMD并把运行结果输出到winform窗体中

2014-12-25 15:53 555 查看
C#调用CMD并把运行结果输出到winform窗体中

代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CmdPerformExe
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
string str = txtText.Text.ToString();

Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";   //获取或设置要启动的应用程序或文档
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true; //接受来自掉用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;  //重定向标准错误输出
p.StartInfo.CreateNoWindow = true; //不显示程序窗口
p.Start();  //启动程序

//向CMD窗口发送输入信息
p.StandardInput.WriteLine(str + "&exit");
p.StandardInput.AutoFlush = true;
string output = p.StandardOutput.ReadToEnd();  //获取CMD窗口的输出信息
textBox1.Text = output;
p.WaitForExit();  //等待程序执行完退出进程;
p.Close();
Console.WriteLine(output);
}
catch (Exception a)
{
FileStream fs=new FileStream(@"D:\A.txt",FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(a);
sw.Close();
fs.Close();
}
}

private void Form1_Load(object sender, EventArgs e)
{

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: