Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

clearing the console

Status
Not open for further replies.

RPelletier

Programmer
Joined
May 21, 2002
Messages
1
Location
US
Is there any way in C# to just clear the console screen and reset the next text location to 0,0? Like the old CLS in basic? I'm just trying to make a simple menu driven program.
 
uh... can someone please replay? im looking for the same thing...
 
Unfortunately, .NET does not yet provide very powerful console funtionality yet (it is suppose to in its next version, but that could be a ways out).

There are a few things you can do though. You can call the Win32 API directly with System.Runtime.InteropServices. You can also create (or use someone else's) C++ code to do the trick as done here.

You might also just consider converting it into a GUI application. That's really what C# is geared towards for the time being as far as user interaction is concerned.
 
A1METALHEAD is right.
Here is a complete example on how to use Native API for console. See the main() below with calls to change the colors and to clear the screen.
Code:
namespace MyConsoleApp

// TestConsole.cs
using System;

namespace MyConsoleApp
{
	
	class TestMyConsole
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			MyConsole con = new MyConsole();
			con.SetConsoleColor(eConsoleColor.PurpleForte,eConsoleColor.SkyBlue);
			System.Console.WriteLine("This is a string1\n");
            		System.Console.WriteLine("This is a string2\n");
			System.Console.WriteLine("Waiting 3 seconds before clear screen call\n");
			System.Threading.Thread.Sleep(3000);
			con.ClearScreen();
			System.Console.WriteLine("Press any key to continue\n");
			int c = System.Console.Read();

		}
	}
}


//MyConcole.cs
using System;

namespace MyConsoleApp
{
	using System;
	using System.Text;
	using System.Runtime.InteropServices;

	
	/// <summary>
	/// List of colors availabe to display text into console.
	/// </summary>
	public enum eConsoleColor
	{   
		Black = 0,
		Blue =         Win32Native.FOREGROUND_BLUE,		
		Green =        Win32Native.FOREGROUND_GREEN,
		SkyBlue =      Win32Native.FOREGROUND_BLUE + Win32Native.FOREGROUND_GREEN,
		Red =          Win32Native.FOREGROUND_RED,
		Purple =       Win32Native.FOREGROUND_BLUE + Win32Native.FOREGROUND_RED,
		Brown =        Win32Native.FOREGROUND_GREEN + Win32Native.FOREGROUND_RED,
		White =        Win32Native.FOREGROUND_BLUE + Win32Native.FOREGROUND_GREEN + 
		Win32Native.FOREGROUND_RED,
		Gray =         Win32Native.FOREGROUND_INTENSIFY,		
		BlueForte =    Win32Native.FOREGROUND_BLUE + Win32Native.FOREGROUND_INTENSIFY,		
		GreenForte =   Win32Native.FOREGROUND_GREEN + Win32Native.FOREGROUND_INTENSIFY,
		SkyBlueForte = Win32Native.FOREGROUND_BLUE + Win32Native.FOREGROUND_GREEN +
		Win32Native.FOREGROUND_INTENSIFY,
		RedForte =     Win32Native.FOREGROUND_RED + Win32Native.FOREGROUND_INTENSIFY,
		PurpleForte =  Win32Native.FOREGROUND_BLUE + Win32Native.FOREGROUND_RED + 
			Win32Native.FOREGROUND_INTENSIFY,
		Yellow =       Win32Native.FOREGROUND_GREEN + Win32Native.FOREGROUND_RED + 
			Win32Native.FOREGROUND_INTENSIFY,
		WhiteForte =   Win32Native.FOREGROUND_BLUE + Win32Native.FOREGROUND_GREEN + 
			Win32Native.FOREGROUND_RED + Win32Native.FOREGROUND_INTENSIFY
	}

	
	/// <summary>
	/// List of available cursor types.
	/// </summary>
	public enum eConsoleCursorType 	{Off, SingleLine,Block, NUMOFCURSORTYPES}

	
	
	/// <summary>
	/// Extended Console class.
	/// </summary>
	public class MyConsole
	{
		//  Local fields.
		static int m_BackColor;
		static Win32Native.CONSOLE_INFO m_Info;
		static IntPtr m_hCon;
		static Win32Native.CURSOR_INFO m_Cinfo;
		static short m_BackAtt;

		
		/// <summary>
		/// Get Console Window Dimensions .
		/// </summary>
		static public int Columns
		{
			get { return m_Info.MaxSize.x; }
		}
		/// <summary>
		/// 
		/// </summary>
		static public int Rows
		{
			get { return m_Info.MaxSize.x; }
		}
		/// <summary>
		///  Set Cursor Position.
		/// </summary>
		/// <param name="y"></param>
		/// <param name="x"></param>
		
		static public void SetConsoleCursorPosition(int y, int x)
		{
			m_Info.CursorPosition.y = (short)(y - 1);
			m_Info.CursorPosition.x = (short)(x - 1);
			if(m_Cinfo.Visible)
			{
				int coord = m_Info.CursorPosition.x + m_Info.CursorPosition.y * 0x10000;
				Win32Native.SetConsoleCursorPosition(m_hCon, coord);
			}
		}
		/// <summary>
		/// Get/Set Console Window Title
		/// </summary>
		
		static public string GetConsoleTitle
		{
			set { Win32Native.SetConsoleTitle(value); }
			get 
			{
				StringBuilder buffer = new StringBuilder(128);
				Win32Native.GetConsoleTitle(buffer, 128);
				return buffer.ToString();
			}
		}

		
		/// <summary>
		///  Set CLS Color.
		/// </summary>
		/// <param name="back"></param>
		/// <param name="fore"></param>
		static public void SetClsColor(eConsoleColor back, eConsoleColor fore)
		{
			m_BackAtt = (short)(((short) back) * 0x10 + (short) fore);
		}
		/// <summary>
		/// Set Color for text.
		/// </summary>
		/// <param name="foreColor"></param>

		static public void SetConsoleColor(eConsoleColor foreColor)
		{
			Win32Native.SetConsoleTextAttribute(m_hCon, (int) foreColor + 16 * m_BackColor);
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="foreColor"></param>
		/// <param name="backColor"></param>
		public void SetConsoleColor(eConsoleColor foreColor, eConsoleColor backColor)
		{
			m_BackColor = (int) backColor;
			SetConsoleColor(foreColor);
		}

		/// <summary>
		/// Change the cursor shape and visibility state.
		/// </summary>
		/// <param name="newType"></param>
		
		static public void SetConsoleCursorType(eConsoleCursorType newType)
		{
			//   Change cursor type.
			switch(newType)
			{
				case eConsoleCursorType.Block:
					m_Cinfo.Size = 100;
					m_Cinfo.Visible = true;
					break;

				case eConsoleCursorType.SingleLine:
					m_Cinfo.Size = 10;
					m_Cinfo.Visible = true;
					break;

				case eConsoleCursorType.Off:
					m_Cinfo.Size = 100;
					m_Cinfo.Visible = false;
					break;
			}
			bool res = Win32Native.SetConsoleCursorInfo(m_hCon, ref m_Cinfo);

			//   Go actual position.
			SetConsoleCursorPosition(m_Info.CursorPosition.y, m_Info.CursorPosition.x);
		}
		/// <summary>
		/// Clear complete screen
		/// </summary>
		public void ClearScreen()
		{
			//   First, fisical clear screen.
			int writted = 0;
			Win32Native.COORD start = new Win32Native.COORD();
			start.x = start.y = 0;
			Win32Native.FillConsoleOutputCharacter(m_hCon, ' ', m_Info.MaxSize.y * m_Info.MaxSize.x, 
				start, ref writted);
			Win32Native.FillConsoleOutputAttribute(m_hCon, m_BackAtt, m_Info.MaxSize.y * m_Info.MaxSize.x,
				start, ref writted);

			//   Cursor go at left/top.
			SetConsoleCursorPosition(1, 1);
		}
		/// <summary>
		///  Static constructor.
		/// </summary>
		public MyConsole()
		{
			//  Try to allocate a console. 
			Win32Native.AllocConsole();
			m_hCon = Win32Native.GetStdHandle(Win32Native.STD_OUTPUT_HANDLE);

			//  Get Console m_Info.
			m_Info = new Win32Native.CONSOLE_INFO();
			Win32Native.GetConsoleScreenBufferInfo(m_hCon, ref m_Info);

			//  Set Standard cursor m_Info.
			m_Cinfo = new Win32Native.CURSOR_INFO();
			SetConsoleCursorType(eConsoleCursorType.SingleLine);

			//  Set standard Background attribute.
			m_BackAtt = (short)(((short) eConsoleColor.Black) * 0x10 + (short) eConsoleColor.White);
		}
	}
}

//Win32NativeAPI.cs
using System;

namespace MyConsoleApp
{
	
	using System;
	using System.Text;
	using System.Configuration.Assemblies;
	using System.Runtime.Remoting;
	using System.Runtime.InteropServices;

	//   Implement static methods to access Console.
	internal sealed class Win32NativeAPI 
	{
		//   Const for dll names.
		internal const String KERNEL32 = "kernel32.dll";
		internal const String USER32   = "user32.dll";

		// These are #defines used to extract handles, and are NOT handles.
		internal const int STD_INPUT_HANDLE = -10;
		internal const int STD_OUTPUT_HANDLE = -11;
		internal const int STD_ERROR_HANDLE = -12;

		// From wincon.h
		internal const int ENABLE_LINE_INPUT  = 0x0002;
		internal const int ENABLE_ECHO_INPUT  = 0x0004;

		// Console Windows define's
		internal const int FOREGROUND_BLUE = 0x01;
		internal const int FOREGROUND_GREEN = 0x02;
		internal const int FOREGROUND_RED = 0x04;
		internal const int FOREGROUND_INTENSIFY = 0x08;
		internal const int BACKGROUND_BLUE = 0x10;
		internal const int BACKGROUND_GREEN = 0x20;
		internal const int BACKGROUND_INTENSIFY = 0x80;

		[StructLayout(LayoutKind.Sequential)]
			internal struct COORD
		{
			internal short x, y;
		}
		
		[StructLayout(LayoutKind.Sequential)]
			internal struct RECT
		{
			short Left, Top, Right, Bottom;
		}
		
		[StructLayout(LayoutKind.Sequential)]
			internal struct CONSOLE_INFO
		{
			internal COORD Size;
			internal COORD CursorPosition;
			internal short Attribute;
			internal RECT  Window;
			internal COORD MaxSize;
		}

		[StructLayout(LayoutKind.Sequential)]
			internal struct CURSOR_INFO
		{
			internal int Size;
			internal bool Visible;
		}


		//   Prototypes for API functions utilized...
		[DllImport(KERNEL32, SetLastError=true)]
		internal static extern IntPtr GetStdHandle(int nStdHandle);

		[DllImport(KERNEL32, CharSet=CharSet.Unicode, SetLastError=true)]
		internal extern static bool SetConsoleTitle(string lpTitleStr);

		[DllImport(KERNEL32, CharSet=CharSet.Unicode, SetLastError=true)]
		internal extern static int GetConsoleTitle(StringBuilder lpBuff, int buffSize);

		[DllImport(KERNEL32, CharSet=CharSet.Unicode, SetLastError=true)]
		internal extern static void WriteConsole(IntPtr handle, string buffer, int bufflen, 
			ref int chrWritted, ref string reserved); 

		[DllImport(KERNEL32, SetLastError=true)]
		internal extern static bool SetConsoleCursorPosition(IntPtr handle, int coord);

		[DllImport(KERNEL32, SetLastError=true)]
		internal extern static bool SetConsoleTextAttribute(IntPtr handle, int attrib);
		
		[DllImport(KERNEL32, SetLastError=true)]
		internal extern static bool AllocConsole();

		[DllImport(KERNEL32, SetLastError=true)]
		internal extern static void GetConsoleScreenBufferInfo(IntPtr Handle, 
			ref CONSOLE_INFO info);
		
		[DllImport(KERNEL32, SetLastError=true)]
		internal extern static bool SetConsoleCursorInfo(IntPtr Handle, ref CURSOR_INFO info);

		[DllImport(KERNEL32, SetLastError=true)]
		internal extern static bool FillConsoleOutputCharacter(IntPtr Handle, char uChar,
			int Len, COORD start, ref int writted);

		[DllImport(KERNEL32, SetLastError=true)]
		internal extern static bool FillConsoleOutputAttribute(IntPtr Handle, short att,
			int Len, COORD start, ref int writted);
	}
}
obislavu
 
WoW, thanks :D you solved a TON of progbs i was having!!!

thanks again!
 
I should write also:
oppcos indication is right.
obislavu

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top