我的程序的GUI。 如何將參數傳遞給cmd.exe並將結果返回到C#Windows應用程序中
我想通過參數爲DIR到CMD.EXE與.NET
Process
類,並得到正確的輸出到C#程序。
來源:
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace MyCmd
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("cmd.exe");
comboBox1.SelectedIndex = 0;
}
private Thread t;
private void button1_Click(object sender, EventArgs e)
{
object[] param = new object[] { comboBox1.Text, txtParams.Text };
if (param.Length > 0 && comboBox1.Text != "")
{
t = new Thread(() => doTask(param));
t.IsBackground = true;
t.Start();
}
else
{
MessageBox.Show("Invalid parameters!");
}
}
private void doTask(object[] param)
{
Process proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = param[0].ToString(),
Arguments = param[1].ToString(),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
this.Invoke((MethodInvoker)delegate
{
txtResponse.Text += line + Environment.NewLine;
});
}
proc.WaitForExit();
}
}
}
這是輸出
我想推出CMD.EXE,然後輸入目錄然後,它列表中的目錄信息到我的應用程序。
更新:
來源更新:
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace MyCmdV2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("cmd.exe");
comboBox1.SelectedIndex = 0;
proc = new Process();
proc.StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
CreateNoWindow = true
};
proc.Start();
}
private Process proc;
private Thread t;
private void button1_Click(object sender, EventArgs e)
{
t = new Thread(() => doIt());
t.IsBackground = true;
t.Start();
}
private void doIt()
{
if (txtParams.Text.ToLower() == "cls")
{
txtResponse.Text = "";
}
else
{
proc.StandardInput.WriteLine(@txtParams.Text);
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
this.Invoke((MethodInvoker)delegate
{
txtResponse.Text += line + Environment.NewLine;
});
}
proc.WaitForExit();
}
}
}
}
這是一個例子查詢only.I需要運行任何EXE程序與參數。 列出我的所有程序到ComboBox
,然後傳遞參數TextBox
。
有些時候我需要把參數作爲IP這樣的地址。 \\192.168.1.2
Ex: psinfo.exe \\192.168.1.2
但是C#它的商店爲\\\\192.168.1.2
。如何刪除參數中的轉義序列字符。
你有沒有調試過,看看參數是否填入startinfo? –
我已經爲此目的創建了一個類庫:https://github.com/lassevk/commander - 它還沒有nuget包,還沒有到那麼遠,我不認爲它生產就緒我不確定我是否已經測試了所有內容,但您可能希望至少查看那裏的代碼。 –