Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / Java

CaptureConsole.DLL - A Universal Console Output Redirector for all Compilers

Rate me:
Please Sign up or sign in to vote.
4.70/5 (41 votes)
28 Oct 2010CPOL7 min read 216.7K   3K   166  
Capture Console Output
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.Threading;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace ConsoleDemo
{
	public class MainForm : System.Windows.Forms.Form
	{
		[DllImport("CaptureConsole.dll", EntryPoint="ExecuteW", CharSet=CharSet.Unicode)]
		static extern UInt32 ExecuteW(string   s_Commandline,
		                              UInt32 u32_FirstConvert,
		                              string   s_CurrentDir,
		                              string   s_Environment,
		                              bool     b_SeparatePipes,
		                              UInt32 u32_Timeout,
		                              [MarshalAs(UnmanagedType.BStr)] out string s_ApiError, 
		                              [MarshalAs(UnmanagedType.BStr)] out string s_StdOut, 
		                              [MarshalAs(UnmanagedType.BStr)] out string s_StdErr);

		public MainForm()
		{
			InitializeComponent();
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);

			Thread i_Thread = new Thread(new ThreadStart(ConsoleThread));
			i_Thread.Start();
		}

		string ExecuteAndPrint(string s_CommandLine, UInt32 u32_FirstConvert, string s_Environ, bool b_SeparatePipes, UInt32 u32_Timeout)
		{
			// Execute Console Application
			string s_ApiError, s_StdOut, s_StdErr;
			UInt32 u32_ExitCode = ExecuteW(s_CommandLine, u32_FirstConvert, null, s_Environ, b_SeparatePipes, u32_Timeout, out s_ApiError, out s_StdOut, out s_StdErr);

            // Format Output
			string s_Out = "";
			if (s_ApiError.Length > 0) // API Error occurred
			{
				s_Out += "\r\n" + s_ApiError;
			}
			else if (b_SeparatePipes)
			{
				s_Out += "\r\n------ STDOUT only :\r\n" + s_StdOut;
				s_Out += "\r\n------ STDERR only :\r\n" + s_StdErr;
				s_Out += "ExitCode= " + u32_ExitCode + "\r\n";
			}
			else
			{
				s_Out += "\r\n------ STDOUT + STDERR in realtime :\r\n" + s_StdOut;
				s_Out += "ExitCode= " + u32_ExitCode + "\r\n";
			}
			return s_Out;
		}

		private void ConsoleThread()
		{
			string s_ExeDir  = Path.GetDirectoryName(Application.ExecutablePath);
			string s_Environ = "UserVariable1=This environment variable was passed to the console!\nUserVariable2=This is User Variable 2\n";

			// -----------------------------------------------------------------------

			String s_Output = "==> Now starting ConsoleTest.exe invisible in the background\r\n";
			s_Output += "    Obtain stdout and stderr by one common pipe:\r\n";
			Print(s_Output);

			// Passing the commandline parameters "Hello" and "World" to the Console application
			string s_Command = string.Format("\"{0}\\ConsoleTest.exe\" \"Hello W�rld\" Test", s_ExeDir);

			s_Output += ExecuteAndPrint(s_Command, 1, s_Environ, false, 120000);

			// -----------------------------------------------------------------------

			s_Output += "\r\n##########################################################################################\r\n";
			s_Output += "\r\n==> Now starting ConsoleTest.exe invisible in the background\r\n";
			s_Output += "    Obtain stdout and stderr by two separate pipes:\r\n";
			Print(s_Output);

			// Passing the commandline parameters "Test" and "Two" to the Console application
			s_Command = string.Format("\"{0}\\ConsoleTest.exe\" Test Two", s_ExeDir);

			s_Output += ExecuteAndPrint(s_Command, 1, s_Environ, true, 120000);

			// -----------------------------------------------------------------------

			s_Output += "\r\n##########################################################################################\r\n";
			s_Output += "\r\n==> Now starting ConsoleTest.bat invisible in the background\r\n";
			Print(s_Output);

			s_Command = string.Format("\"{0}\\ConsoleTest.bat\"  \"Hello W�rld\" Test", s_ExeDir);

			s_Output += ExecuteAndPrint(s_Command, 0, s_Environ, false, 120000);

			Print(s_Output);
		}

		/// <summary>
		/// Write into the textbox always from the GUI thread.
		/// Print() is called twice:
		/// First in the context of the ConsoleThread (InvokeRequired = true) 
		/// and then it calls itself in the context of the GUI thread (InvokeRequired = false)
		/// </summary>
		delegate void delPrint(string s_Text);
		
		void Print(string s_Text)
		{
		    if (InvokeRequired) 
		        Invoke(new delPrint(Print), new object[]{s_Text});
		    else 
		        textBox.Text = s_Text;
		}

		#region Windows Form Designer generated code

		private System.Windows.Forms.TextBox textBox;
		private System.ComponentModel.Container components = null;

		[STAThread]
		static void Main() 
		{
			Application.Run(new MainForm());
		}

		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.textBox = new System.Windows.Forms.TextBox();
			this.SuspendLayout();
			// 
			// textBox
			// 
			this.textBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.textBox.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.textBox.Location = new System.Drawing.Point(16, 16);
			this.textBox.Multiline = true;
			this.textBox.Name = "textBox";
			this.textBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
			this.textBox.Size = new System.Drawing.Size(744, 424);
			this.textBox.TabIndex = 0;
			this.textBox.Text = "";
			// 
			// MainForm
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(776, 461);
			this.Controls.Add(this.textBox);
			this.MaximizeBox = false;
			this.Name = "MainForm";
			this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Console Demo C#";
			this.ResumeLayout(false);

		}
		#endregion
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) ElmüSoft
Chile Chile
Software Engineer since 40 years.

Comments and Discussions