[英]C# console application display remaining time or percentage from another running process
i have a c# console program.Im using .net 2.0.我有一个 c# 控制台程序。我正在使用 .net 2.0。 Im launching an exe from my console program.
我从我的控制台程序启动一个 exe。 That exe shows progress bar on taskbar.
该exe在任务栏上显示进度条。
Here i want to read progress percentage from that exe and want to display (1% 2% 3% etc) on my console app program.在这里,我想从该 exe 中读取进度百分比,并希望在我的控制台应用程序上显示(1% 2% 3% 等)。
(i dont want to display whole output of that exe into my program. i also did test of setting following code but it shows all output of that exe i only want to display percentage ) (我不想在我的程序中显示该 exe 的整个 output。我还测试了设置以下代码,但它显示了该 exe 的所有 output 我只想显示百分比)
Is this possible using .net 2.0?这可以使用 .net 2.0 吗?
im beginner in c#我是 c# 的初学者
i have following working code我有以下工作代码
string fullName = "A.exe" ;
Process p1 = new Process();
p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p1.StartInfo.UseShellExecute = true;
p1.StartInfo.FileName = fullName;
p1.Start();
p1.WaitForExit();
To read program's progress, you should redirect the standard output and define a method DataReceived that handles OutputDataReceived event of the specified Process instance.要读取程序的进度,您应该重定向标准 output 并定义一个DataReceived方法来处理指定Process实例的OutputDataReceived事件。 This method, for example, gets the percentage of the text, assuming it contains a single number (see GetPercent ), and updates the progress information as you see fit.
例如,此方法获取文本的百分比,假设它包含一个数字(请参阅GetPercent ),并根据您认为合适的方式更新进度信息。
static class Program
{
static void Main(string[] args)
{
using (Process proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "A.exe", // Type filename here.
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false
}
})
{
proc.OutputDataReceived += DataReceived;
proc.Start();
proc.WaitForExit();
}
}
// Updates a progress value.
static void DataReceived(object sender, DataReceivedEventArgs e)
{
// The e.Data property contains programs output string.
// Esc-symbol \r means overwriting the current line.
Console.Write("\rTotal " + GetPercent(e.Data) + " completed.");
}
// Gets the percentage from the output string.
static string GetPercent(string data)
{
// The regular expression that finds a number from a string.
Regex regex = new Regex(@"([^\d]|^)\d{1,2}([^\d]|$)");
Match match = regex.Match(data);
return match.Value;
}
}
This code should be modified for the specific output format of your program.此代码应针对您程序的特定 output 格式进行修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.