我正在處理cmd輸出到RichTextBox. 有沒有辦法將所有進度(%)合并/加入到單行中RichTextBox?而不是為每個 % 創建一行。我希望它是這樣cmd的(除了洗掉現在的空行)。
private async void btnStart_Click(object sender, EventArgs e){
await Task.Factory.StartNew(() =>
{
Execute1("Prtest.exe", " x mode2 C:\\input.iso C:\\output.iso");
});
}
private void Execute1(string filename, string cmdLine){
var fileName = filename;
var arguments = cmdLine;
var info = new ProcessStartInfo();
info.FileName = fileName;
info.Arguments = arguments;
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.CreateNoWindow = true;
using (var p = new Process())
{
p.StartInfo = info;
p.EnableRaisingEvents = true;
p.OutputDataReceived = (s, o) =>
{
tConsoleOutput(o.Data);
};
p.ErrorDataReceived = (s, o) =>
{
tConsoleOutput(o.Data);
};
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
}
}
public void tConsoleOutput(string text){
BeginInvoke(new Action(delegate ()
{
rtConsole.AppendText(text Environment.NewLine);
rtConsole.ScrollToCaret();
//remove empty lines
rtConsole.Text = Regex.Replace(rtConsole.Text, @"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);
}));
}
實際cmd.exe輸出:
Processing: 100%
Sectors: 43360
Completed.
C# RichTextBox(rtConsole) 輸出:
Processing: 2%
Processing: 4%
Processing: 7%
Processing: 9%
Processing: 11%
Processing: 14%
Processing: 16%
Processing: 39%
Processing: 100%
Sectors: 43360
Completed.
更新:已解決

非常感謝@Jackdaw
uj5u.com熱心網友回復:
試試下面的方法:
static public void tConsoleOutput(RichTextBox rtb, string line)
{
var pattern = @"^Processing: \d{1,3}%.*$";
if (!line.EndsWith(Environment.NewLine))
line = Environment.NewLine;
var isProcessing = Regex.Match(line, pattern).Success;
rtb.Invoke((MethodInvoker)delegate
{
var linesCount = rtb.Lines.Length;
if (linesCount > 1 && isProcessing)
{
var last = rtb.Lines[linesCount - 2];
if (Regex.Match(last, pattern).Success)
{
var nlSize = Environment.NewLine.Length;
// Update latest line
var sIndex = rtb.GetFirstCharIndexFromLine(linesCount - nlSize);
var eIndex = sIndex last.Length nlSize;
rtb.Select(sIndex, eIndex - sIndex);
rtb.SelectedText = line;
return;
}
}
rtb.AppendText(line);
});
}
看起來像這樣:

uj5u.com熱心網友回復:
我不知道你寫的代碼(或者,如果不是你的,它來自哪里),但我可以告訴你,最簡單的方法是\r字符,它將你的插入符號重置為開頭線。
這意味著您必須確保不要使用Console.WriteLine而是Console.Write代替。
一個例子:
Console.Write("00.00% Done");
Thread.Sleep(1500);
Console.Write("\r100.00% Done");
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432584.html
