C# Source Code: Console window utility class
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Console window utility class
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Monday, November 14, 2005
Hits:
2050
Category:
General/Framework
Article:
Below is the console utility class which extends the .NET Console class. The class has a number of useful functions including setting the title, changing text attributes (inc forecolor and backcolor) and creating and destroying the console window. using System; using System.Runtime.InteropServices; using System.Text; ///
/// www.VBusers.com. Static library class providing a number of useful functions for using Console windows. /// By Andrew Baker. ///
public class ConsoleLib { #region Enums ///
/// Enumeration containing console attributes flags. ///
public enum ConsoleAttributes: int { ///
/// Text color contains blue. ///
ForegroundBlue = 0x0001, ///
/// Text color contains green. ///
ForegroundGreen = 0x0002, ///
/// Text color contains red. ///
ForegroundRed = 0x0004, ///
/// Text color is intensified. ///
ForegroundIntensity = 0x0008, ///
/// Background color contains blue. ///
BackgroundBlue = 0x0010, ///
/// Background color contains green. ///
BackgroundGreen = 0x0020, ///
/// Background color contains red. ///
BackgroundRed = 0x0040, ///
/// Background color is intensified. ///
BackgroundIntensity = 0x0080, ///
/// Leading byte. ///
LeadingByte = 0x0100, ///
/// Trailing byte. ///
TrailingByte = 0x0200, ///
/// Top horizontal. ///
GridHorizontal = 0x0400, ///
/// Left vertical. ///
GridLeftVertical = 0x0800, ///
/// Right vertical. ///
GridRightVertical = 0x1000, ///
/// Reverse foreground and background attributes ///
ReverseVideo = 0x4000, ///
/// Underscore. ///
Underscore = 0x8000 } #endregion Enums #region Constants ///
/// Gets the standard out handle. ///
private const int STD_OUTPUT_HANDLE = -11; ///
/// Gets the standard input handle. ///
private const int STD_INPUT_HANDLE = -10; #endregion #region Structs ///
/// Structure to hold data read from console stream. ///
[StructLayout(LayoutKind.Sequential)] private struct INPUT_RECORD { public ushort EventType; public uint bKeyDown; public ushort wRepeatCount; public ushort wVirtualKeyCode; public ushort wVirtualScanCode; public char UnicodeChar; public uint dwControlKeyState; } #endregion #region Console API Imports ///
/// The ReadConsoleInput function reads data from a console input buffer and removes it from the buffer. ///
///
Handle to the console input buffer. ///
Pointer to an array of INPUT_RECORD structures that receives the input buffer data. /// The total size of the array required will be less than 64K. ///
Size of the array pointed to by /// the lpBuffer parameter, in array elements. ///
Pointer to a variable that /// receives the number of input records read. ///
If the function succeeds, the return value is nonzero.
[DllImport("kernel32", CharSet=CharSet.Auto, SetLastError=true)] private static extern bool ReadConsoleInput( IntPtr hConsoleInput, [Out] INPUT_RECORD[] lpBuffer, int nLength, out int lpNumberOfEventsRead); ///
/// The WriteConsole function writes a character string to /// a console screen buffer beginning at the current cursor location. ///
///
Handle to the console screen buffer. The handle must have the GENERIC_WRITE access right. ///
Pointer to a buffer that contains characters to be written to the console screen buffer. ///
Number of TCHARs to write. ///
Pointer to a variable that receives the number of TCHARs actually written ///
Reserved; must be NULL. ///
If the function succeeds, the return value is nonzero.
[DllImport("kernel32.dll")] private static extern bool WriteConsole( IntPtr hConsoleOutput, string lpBuffer, uint nNumberOfCharsToWrite, out uint lpNumberOfCharsWritten, IntPtr lpReserved); ///
/// The AllocConsole function allocates a new console for the calling process. ///
///
If the function succeeds, the return value is nonzero.
[DllImport("kernel32.dll")] private static extern Boolean AllocConsole(); ///
/// The SetConsoleTitle function sets the title for the current console window. ///
///
Pointer to a null-terminated string that contains /// the string to be displayed in the title bar of the console window. ///
If the function succeeds, the return value is nonzero.
[DllImport("kernel32.dll")] private static extern bool SetConsoleTitle(string lpConsoleTitle); ///
/// The GetStdHandle function retrieves a handle for the standard input, /// standard output, or standard error device. ///
///
Standard device for which a handle is to be returned. ///
If the function succeeds, the return value is a handle to the specified device, /// or a redirected handle set by a previous call to SetStdHandle
[DllImport("kernel32.dll")] private static extern IntPtr GetStdHandle(int nStdHandle); ///
/// The SetConsoleTextAttribute function sets the attributes of characters written to the console screen /// buffer by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsole function. /// This function affects text written after the function call. ///
///
Handle to a console screen buffer. ///
Character attributes. ///
If the function succeeds, the return value is nonzero.
[DllImport("kernel32.dll", SetLastError=true)] private static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, ConsoleAttributes wAttributes); ///
/// The FreeConsole function detaches the calling process from its console. ///
///
If the function succeeds, the return value is nonzero.
[DllImport("kernel32.dll", SetLastError=true)] private static extern int FreeConsole(); #endregion Console API Imports #region Constructors ///
/// Default constructor ///
private ConsoleLib() { // Intentionally blank } #endregion Constructors #region Public Methods ///
/// Sets the specified attribute for the standard output displayed on a console window. ///
///
The console attributes to set. public static void SetAttribute( ConsoleAttributes attributes ) { // Get std output handle IntPtr hOut = GetStdHandle(STD_OUTPUT_HANDLE); if ( hOut != IntPtr.Zero ) { // Set attribute SetConsoleTextAttribute( hOut, attributes); } } ///
/// Returns true if the process has a standard output console window attached to it. ///
public static bool HasConsole() { // Check if the std output handle exists return GetStdHandle(STD_OUTPUT_HANDLE) != IntPtr.Zero; } ///
/// Closes the console window associated with this application. ///
///
Returns true on success, else false.
public static bool ExitConsole() { return FreeConsole() != 0; } ///
/// Creates a console window. ///
///
Returns true on success, else false.
public static bool CreateConsole() { return AllocConsole(); } ///
/// Sets the specified attribute for the standard output displayed on a console window. ///
///
The text to write to the console window. ///
The console attributes to set. public static void WriteFormatted( string text, ConsoleAttributes attributes ) { // Set attributes SetAttribute( attributes ); // Write text WriteLine( text ); // Clear attributes SetAttribute( (ConsoleAttributes)0 ); } ///
/// Sets the console window title. ///
///
The title of the console window. public static void SetTitle( string title ) { // Set title SetConsoleTitle( title); } ///
/// Writes a character string to a console screen buffer beginning at the current cursor location. ///
///
The text to be written to the console screen buffer. ///
Returns true on success, else false.
public static bool WriteLine( string text ) { return Write( text + Environment.NewLine ); } ///
/// Writes a character string to a console screen buffer beginning at the current cursor location. ///
///
The text to be written to the console screen buffer. ///
Returns true on success, else false.
public static bool Write( string text ) { if ( text == null ) { return false; } // Get std output handle IntPtr hOut = GetStdHandle(STD_OUTPUT_HANDLE); if ( hOut != IntPtr.Zero ) { uint ignore; return WriteConsole( hOut , text, (uint)text.Length, out ignore, IntPtr.Zero ); } return false; } ///
/// Reads the next line of characters from the standard input stream. ///
///
Returns the next line of characters from the standard input stream.
public static string ReadLine() { // Just delegate the call (as the Console class doesn't cache the std out handle) return Console.ReadLine(); } #endregion Public Methods }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet