我编写了一个自定义控制台应用程序,它将输出重定向到我正在运行的命令(在我正在运行的屏幕截图'cmd.exe'中)到richtextbox控件。使用的字体是'Lucida Console',它与'cmd.exe'本身使用的字体相同。
我遇到的问题是某些字符没有正确显示,但它们是该命令的正确字符。最好的猜测,这些是ANSI终端字符,必须进行转义/处理/其他,但我不确定。所以这不会成为一个XY问题,我会清楚地表达我的意图:
我想在richtextbox中显示这些字符,与运行'cmd.exe'时显示的字符相同。我使用的语言是.NET Framework 4.5上的C#,没有额外的控件。我正在重定向System.Diagnostics.Process.Start()和RichTextBox控件的输出/输入。
相关守则:
void processInterace_OnProcessOutput( object sender, ProcessEventArgs args ) {
// Write the output
string outp = Encoding.GetEncoding(437).GetString(Encoding.GetEncoding(437).GetBytes(args.Content.Substring(lastInput.Length).ToCharArray()));
WriteOutput( outp, ForeColor );
lastInput="";
// Fire the output event.
FireConsoleOutputEvent( args.Content );
}
public void WriteOutput( string output, Color color ) {
if ( string.IsNullOrEmpty( lastInput )==false&&
( output==lastInput||output.Replace( "\r\n", "" )==lastInput ) )
return;
if ( !this.IsHandleCreated )
return;
Invoke( (Action)( () => {
// Write the output.
richTextBoxConsole.Focus();
richTextBoxConsole.SelectionColor=color;
richTextBoxConsole.SelectedText+=output;
inputStart=richTextBoxConsole.SelectionStart;
} ) );
}
public void StartProcess( string fileName, string arguments ) {
// Are we showing diagnostics?
if ( ShowDiagnostics ) {
WriteOutput( "Preparing to run "+fileName, DiagnosticsColor );
if ( !string.IsNullOrEmpty( arguments ) )
WriteOutput( " with arguments "+arguments+"."+Environment.NewLine, DiagnosticsColor );
else
WriteOutput( "."+Environment.NewLine, DiagnosticsColor );
}
// Start the process.
processInterace.StartProcess( fileName, arguments );
// If we enable input, make the control not read only.
if ( IsInputEnabled )
richTextBoxConsole.ReadOnly=false;
}
钩子(重要)
processInterace.OnProcessOutput+=processInterace_OnProcessOutput;
更新
所以我决定尝试一种新方法来解决这个问题。由于ProcessInterface
似乎无法真正控制更改从流程中收到的输出的编码,因此我决定尝试使用原始Process
接口,如下所示:
public partial class Form1 : Form {
Process process { get; set; }
ProcessStartInfo startinfo { get; set; }
public Form1() {
InitializeComponent();
process = new Process();
startinfo = new ProcessStartInfo() {
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
StandardErrorEncoding = System.Text.Encoding.GetEncoding(437),
StandardOutputEncoding = System.Text.Encoding.GetEncoding(437),
UseShellExecute = false,
ErrorDialog = false,
CreateNoWindow = true,
WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
//WindowStyle=System.Diagnostics.ProcessWindowStyle.Normal
};
}
void process_ErrorDataReceived( object sender, DataReceivedEventArgs e ) {
Invoke( (Action)( () => {
cb.Text+=e.Data+"\n";
} ) );
}
void process_Exited( object sender, EventArgs e ) {
this.Text = "Exited";
}
private void Form1_Load( object sender, EventArgs e ) {
process.StartInfo.Arguments = "/K tree";
startinfo.FileName="cmd.exe";
process=new Process {
StartInfo = startinfo
};
process.OutputDataReceived+=process_OutputDataReceived;
process.ErrorDataReceived+=process_ErrorDataReceived;
process.Exited+=process_Exited;
process.EnableRaisingEvents=true;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
}
void process_OutputDataReceived( object sender, DataReceivedEventArgs e ) {
Invoke( (Action)( () => {
cb.Text+=e.Data + "\n";
} ) );
}
}
这导致了一个新问题。我没有收到有关所有新数据的事件通知 - 仅在回车符中终止的新行上。输出示例如下图所示:
当我在最近的示例中更改form_Load
时,您可以看到这最终解决了编码问题,但是存在一个新问题,即在从控制台发送回车之前不会返回最后一行:
private async void Form1_Load( object sender, EventArgs e ) {
process.StartInfo.Arguments = "";
startinfo.FileName="cmd.exe";
process=new Process {
StartInfo = startinfo
};
process.OutputDataReceived+=process_OutputDataReceived;
process.ErrorDataReceived+=process_ErrorDataReceived;
process.Exited+=process_Exited;
process.EnableRaisingEvents=true;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
await process.StandardInput.WriteLineAsync( @"tree d:\sqlite" );
}
答案 0 :(得分:1)
您可以使用File类对编码的控制。
var tempOutPath = Path.GetTempFileName();
var chcp = Process.Start("cmd.exe", $@" /c chcp >""{tempOutPath}""");
chcp.WaitForExit();
var encoding = Int32.Parse(File.ReadAllText(tempOutPath, Encoding.GetEncoding(437)).Replace("Active code page:", ""));
var tree = Process.Start("cmd.exe", $@" /c tree ""C:\Program Files\WinCDEmu"" >""{tempOutPath}""");
tree.WaitForExit();
var result = File.ReadAllText(tempOutPath, Encoding.GetEncoding(encoding));
File.Delete(tempOutPath);