读书人

C#中展示控制台输出

发布时间: 2011-12-26 23:09:58 作者: rapoo

C#中显示控制台输出
我使用VC做了一个DLL,在C#中调用。为了适时显示运行信息,使用了cout输出各种信息,现在的问题是我如果在C#中将这些信息显示出来。

[解决办法]
可以选择两种:
1、控制台的重定向;
2、如果你的DLL中导出的函数是返回char*的,那么取回来再自行输出。
[解决办法]
在控制台程序中引用DLL,再输出
[解决办法]
控制台应用中引用,然后进行调用
[解决办法]
通过Stream,可以捕获控制台输出,也可以把程序信息输出到控制台
例程是捕获CMD命令的控制台输出,引用DLL,捕获控制台输出是一样的。

C# code
// 代码如下:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace CommandTest{    public partial class FrmRunCommand : Form    {        System.IO.StreamWriter sw;  // 定义输出流 sw 作为Shell的标准输入,即命令         System.IO.StreamReader sr;  // 定义输出流 sr 作为Shell的标准输出,即正常结果        System.IO.StreamReader err; // 定义输出流 err 作为Shell的错误输出,即出错结果        System.Diagnostics.Process p = new System.Diagnostics.Process();        System.Diagnostics.ProcessStartInfo psI = new System.Diagnostics.ProcessStartInfo(System.Environment.GetEnvironmentVariable("ComSpec"));    public FrmRunCommand()        {            InitializeComponent();        }    private void btnRun_Click(object sender, EventArgs e)        {                       psI.UseShellExecute =false ;            psI.RedirectStandardInput   =   true;            psI.RedirectStandardOutput   =   true;            psI.RedirectStandardError   =   true;            psI.CreateNoWindow   =   true;            p.StartInfo = psI;        Cursor = System.Windows.Forms.Cursors.WaitCursor;                p.Start();             sw = p.StandardInput;             sr = p.StandardOutput;            err = p.StandardError;        sw.AutoFlush = true;        if(coboCommand.Text != "")            {                sw.WriteLine(coboCommand.Text);            }            else            {                sw.WriteLine("echo 未输入命令");            }            sw.Close();        tbResult.Text = "输出结果为:"+sr.ReadToEnd();            tbResult.Text += "\n错误信息:\n"+err.ReadToEnd();        Cursor = System.Windows.Forms.Cursors.Default;        }    }}
[解决办法]
C# 中调用 C++ 编写的动态链接库函数,如果需要出口参数输出,则需要使用指针,对于字符串,则需要使用双重指针,对于 C# 的导入定义,则需要使用引用(ref)定义。

读书人网 >C#

热点推荐