我想在 WPF 中创建一个命令提示符,用户可以在其中键入命令并在同一窗口中获取输出,这正是原始命令提示符的工作方式。
最初我使用Process.Start()
并将其放入另一个线程中,以免阻塞主线程。我使用StreamReader和StreamWriter来编写和捕获输出。但是,我无法连续侦听输出或编写命令。
这是我到目前为止的代码 -
public class TerminalController
{
public Process CmdProcess { get; set; }
public StreamReader Reader { get; set; }
public StreamWriter Writer { get; set; }
public void Init()
{
if (CmdProcess != null)
{
try
{
Close();
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
CmdProcess = new Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "cmd";
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
CmdProcess.StartInfo = startInfo;
CmdProcess.Start();
Writer = CmdProcess.StandardInput;
StartReading();
}
public void Init(string command)
{
if (CmdProcess != null)
{
try
{
Close();
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
CmdProcess = new Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "cmd";
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
CmdProcess.StartInfo = startInfo;
CmdProcess.Start();
}
private void Write(String command)
{
using (Writer = CmdProcess.StandardInput)
{
Writer.Write(command);
}
}
private void StartReading()
{
using (Reader = CmdProcess.StandardOutput)
{
RaiseTerminalReadEvent(null, Reader.ReadToEnd());
}
}
public async void RunCommand(String command)
{
RaiseTerminalWriteEvent(command);
await Task.Run(() => Write(command));
await Task.Run(() => StartReading());
//Close();
}
public Task InitAsync()
{
return Task.Run(() => Init());
}
public void Close()
{
try
{
CmdProcess.Close();
Reader.Close();
Writer.Close();
CmdProcess = null;
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
internal Task RunCommandAsync(string command)
{
return Task.Run(() => RunCommand(command));
}
}
我只能运行一次命令,这是我发送 dir 命令时的输出 -
dir
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.
E:MicrosoftWPFExampleExamplebinDebug>More?
如果我再次发送命令,它会给出以下异常 -
Cannot write to a closed TextWriter.
at System.IO.__Error.WriterClosed()
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.StreamWriter.Write(String value)
at Example.Controllers.TerminalController.Write(String command) in e:MicrosoftWPFExampleExampleControllersTerminalController.cs:line 91
那么我怎样才能连续运行命令并侦听输出。我是否需要每次都创建一个新流程?还有其他选择吗?
您的using
块会在您首次使用流时立即处理它们。
因此,您不能再次使用它们。
别这样。