c#学习4

下面来学习一下控制台程序与窗体的连接问题。

整体思路如下:

先建一个控制台程序,放到一个路径中,然后再写一个窗体,在代码中实现窗体与控制台之间的连接。

首先需要先写一个控制台程序。例如一个简单的程序如下。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace ConsoleApplication1

{    

class Program    

{       

  static void Main(string[] args)    

     {            

System.Console.WriteLine("Hello,World");    

     }

    }

}

然后打开vc建一个windows窗体程序。例如,

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Runtime.InteropServices;

using System.Windows.Forms;

namespace CRC

{   

  public partial class Form1 : Form    

{       

  public Form1()       

  {            

InitializeComponent();      

   }

        private void button1_Click(object sender, EventArgs e)      

   {            

Process cmd = new Process();          

   cmd.StartInfo.FileName = "D:\\visual studio\\workplace\\CRC\\CRC\bin\\Debug\\CRC.exe";  //控制台程序的目录。

   cmd.StartInfo.UseShellExecute = false;            

   cmd.StartInfo.RedirectStandardInput = true;            

   cmd.StartInfo.RedirectStandardOutput = true;

   cmd.StartInfo.CreateNoWindow = true;

   cmd.Start();       

    this.listBox1.Items.Add(cmd.StandardOutput.ReadToEnd());     //将控制台程序的内容返回到窗体的listbox中。  

  }

        private void textBox2_TextChanged(object sender, EventArgs e)     

    {              

   }

        private void textBox1_TextChanged(object sender, EventArgs e)    

     {       

          }

    }

}

图上的组件可由工具箱里的组件拖拽即可。

上面是建立的窗体,这样就基本实现了窗体与控制台程序的连接。

 

posted on 2015-04-06 16:54  石家名  阅读(118)  评论(0编辑  收藏  举报