zoukankan      html  css  js  c++  java
  • 异步获取CMD命令行输出内容

    当控制台命令使用process.Start(); 后可以直接显示输出内容,当然它是异步显示的不用等程序结束。代码如下:

    using System;
    using
     System.Collections.Generic;
    using
     System.ComponentModel;
    using
     System.Data;
    using
     System.Drawing;
    using
     System.Linq;
    using
     System.Text;
    using
     System.Windows.Forms;
    using
     System.Diagnostics;

    namespace
     testApplication1
    {
        
    public partial class
     Form1 : Form
        {
            
    public
     Form1()
            {
                InitializeComponent();
            }

            
    private void button1_Click(object
     sender, EventArgs e)
            {
                
    using (Process process = new
     System.Diagnostics.Process())  
                { 
                    process.StartInfo.FileName 
    = "ping"

                    process.StartInfo.Arguments 
    = "127.0.0.1 -t"
    ;
                    process.StartInfo.UseShellExecute 
    = false
    ;
                    process.StartInfo.CreateNoWindow 
    = true
    ;  
                    process.StartInfo.RedirectStandardOutput 
    = true

                    
                    process.Start(); 
                    process.BeginOutputReadLine();  
                    process.OutputDataReceived 
    += new
     DataReceivedEventHandler(process_OutputDataReceived);  
                }  
            }

            
    private void process_OutputDataReceived(object
     sender, DataReceivedEventArgs e) 
            {
                
    if (!string
    .IsNullOrEmpty(e.Data))
                    
    this.AppendText(e.Data +
     Environment.NewLine);   
            }
            
    public delegate void AppendTextCallback(string
     text);  
            
            
    public void AppendText(string
     text)  
            { 
                
    if (this
    .textBox1.InvokeRequired)  
                {  
                    AppendTextCallback d 
    = new
     AppendTextCallback(AppendText);  
                    
    this
    .textBox1.Invoke(d, text); 
                } 
                
    else
     
                {  
                    
    this
    .textBox1.AppendText(text);                  
                } 
            }  
        }
    }

    程序是一个ping -t的示例:

  • 相关阅读:
    iOS开发- UICollectionView详解+实例
    iOS 8出色的跨应用通信效果:解读Action扩展
    iOS开发宝典:String用法大全
    Masonry介绍与使用实践
    UILabel 行间距设置
    libc++abi.dylib: terminate_handler unexpectedly threw an exception错误小结
    适配iOS 8备忘录 开始启动(持续更新。。。1130)
    “System.AccessViolationException”类型的未经处理的异常在 System.Data.dll 中发生 其他信息: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏
    HighCharts 详细使用及API文档说明
    跟我一起从零开始学WCF系列课程
  • 原文地址:https://www.cnblogs.com/wwwzzg168/p/3570672.html
Copyright © 2011-2022 走看看