【问题标题】:Using extended ASCII to create a tree in a WinForms RichTextBox control使用扩展 ASCII 在 WinForms RichTextBox 控件中创建树
【发布时间】:2016-03-31 01:17:50
【问题描述】:

我编写了一个自定义控制台应用程序,它将输出重定向到/来自我正在运行的命令(在屏幕截图中我正在运行'cmd.exe')到富文本框控件。使用的字体是“Lucida Console”,与“cmd.exe”本身使用的字体相同。

我面临的问题是某些字符没有正确显示,但是它们是该命令的正确字符。充其量猜测,这些是必须转义/处理/任何东西的ANSI终端字符,但我不确定。所以这不会成为一个 XY 问题,我会明确我的意图:

我想在富文本框中显示这些字符,就像它们在运行“cmd.exe”时一样。我使用的语言是 .NET Framework 4.5 上的 C#,没有额外的控件。我正在重定向 System.Diagnostics.Process.Start() 和 RichTextBox 控件的输出/输入。

我的项目

CMD.EXE

相关代码:

    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" );

}

【问题讨论】:

  • 发生 AAAA 是因为 RichTextBox 不知道如何解释那些扩展的 ASCII 字符。
  • @RobertHarvey - 我正在考虑使用String.Replace() 类型的hack,但是这只描述了一小部分字符,并没有真正解决问题。我知道这些字符是可显示的。如果您将tree(通过 cmd.exe)的输出复制到其他任何内容中,您实际上会得到“AAAA”。(又名记事本)
  • @RobertHarvey - 可能,但是您知道要测试的编码吗?我认为这可能不仅仅是编码问题,而是与处理 ANSI / 终端特定输出有关。
  • en.wikipedia.org/wiki/Code_page_437。您还需要一个固定宽度的字体。

标签: c# console richtextbox


【解决方案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);

【讨论】:

  • 我实际上已经解决了这个问题,而无需从外部文件中读取。我将这种方法视为一种潜在的解决方法,但是我想出了一种获取所有数据的方法。一旦我弄清楚了这个插入符号的事情,就会发布一个解决方案。颜色是……呃……
  • 整个项目(具有此功能,无需像您在此处那样通过管道传输到文件)可以作为控制台代码找到我在这里提出的另一个问题 > stackoverflow.com/questions/36350974/… 。由于您的解决方案是执行此操作的一种方法,并且为了保留此链接,我将此答案标记为正确。您能否在您的答案中添加此 SO 链接参考,因为它是一个更彻底的解决方案。谢谢
猜你喜欢
  • 2011-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多