我想捕获Perl程序的输出,并在C#窗体上的文本框中显示输出数据(屏幕上的字符串)。
下面是我的主要C#代码:
public partial class frmMain : Form
{
private Process myProcess = null;
public frmMain()
{
InitializeComponent();
}
public delegate void UpdateUIDelegate(string data);
private void btnRun_Click(object sender, EventArgs e)
{
myProcess = new Process();
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("perl.exe");
myProcessStartInfo.Arguments = "test.pl";
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcessStartInfo.CreateNoWindow = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.OutputDataReceived += new DataReceivedEventHandler(myProcess_OutputDataReceived);
myProcess.Start();
myProcess.BeginOutputReadLine();
}
void myProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (txtOutput.InvokeRequired)
{
UpdateUIDelegate updateDelegate = new UpdateUIDelegate(UpdateUI);
this.Invoke(updateDelegate, e.Data);
}
}
void UpdateUI(string data)
{
txtOutput.Text += data + "\r\n";
}
}和test.pl的代码:
my @a = qw{1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19};
my @b = qw{a b c d e f g h i j k l m n o p q r s };
print 'start' . "\n";
while ( my ( $item1, $item2) = ( splice (@a, 0, 1), splice (@b, 0, 1) ) ) {
print 'Item 1: ' . $item1 . "\n";
print 'Item 2: ' . $item2 . "\n";
warn 'Finish one item' . "\n";
sleep(1);
}我有一个问题,在Perl完成之前,输出数据只显示在文本框中。
更有趣的是,当我发现,如果我对控制台应用程序(C#)执行同样的操作,一切似乎都很正常。
以下是控制台应用程序的代码:
class Program
{
static void Main(string[] args)
{
Process myProcess = new Process();
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("perl.exe");
myProcessStartInfo.Arguments = "test.pl";
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.OutputDataReceived += new DataReceivedEventHandler(myProcess_OutputDataReceived);
myProcess.Start();
myProcess.BeginOutputReadLine();
Console.Read();
}
static void myProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
}我试图弄清楚我的表单应用程序发生了什么,但仍然找不到任何线索。还有一件事是,我不能得到警告消息与windows窗体应用程序。
发布于 2009-03-16 12:14:18
首先,您必须更新事件处理程序
void myProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (txtOutput.InvokeRequired)
{
UpdateUIDelegate updateDelegate = new UpdateUIDelegate
(UpdateUI);this.Invoke(updateDelegate, e.Data);
}
else UpdateUI(e.Data);
}并将此行添加到您的btnRun_Click中
proc.WaitForExit();https://stackoverflow.com/questions/649993
复制相似问题