473,729 Members | 2,079 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Colour Console Application

I am working on a little app which uses colour in the console window. I have
created a class to extend the console functionality but the ClearScreen
method does not work correctly. I am enclosing a complete project
to show what happens. If anybody has an idea of how to fix
this, please let me know.

Yes I am aware that this is all in .Net 2.

Thanks in advance.

Publicjoe

----- Main.cs -----
using System;
using Publicjoe.Conso le;

namespace ColourTest
{
class MainClass
{
public static void Main(string[] args)
{
ConsoleExt TextChange = new ConsoleExt();
Console.WriteLi ne("Original Colors");
Console.WriteLi ne("Press Enter to Begin");
Console.ReadLin e();
TextChange.Text Color((int)Cons oleExt.Foregrou nd.Green +
(int)ConsoleExt .Foreground.Int ensity);
Console.WriteLi ne("THIS TEXT IS GREEN");
Console.WriteLi ne("Press Enter to change colors again");
Console.ReadLin e();
TextChange.Text Color((int)Cons oleExt.Foregrou nd.Red +
(int)ConsoleExt .Foreground.Blu e +
(int)ConsoleExt .Foreground.Int ensity);
Console.WriteLi ne("NOW THE TEXT IS PURPLE");
Console.WriteLi ne("Press Enter to change colors again");
Console.ReadLin e();
TextChange.Text Color((int)Cons oleExt.Foregrou nd.Blue +
(int)ConsoleExt .Foreground.Int ensity +
(int)ConsoleExt .Background.Gre en +
(int)ConsoleExt .Background.Int ensity);
Console.WriteLi ne("NOW THE TEXT IS BLUE AND BACKGROUND OF IT IS
GREEN");
Console.WriteLi ne("Press Enter change everything back to normal");
Console.ReadLin e();
TextChange.Rese tColor();
TextChange.Clea rScreen();
Console.WriteLi ne("Back to Original Colors");
Console.WriteLi ne("Press Enter to Terminate");
Console.ReadLin e();
}
}
}
----- End -----

----- ConsoleExt.cs ----
using System;
using System.Runtime. InteropServices ;

namespace Publicjoe.Conso le
{
public class ConsoleExt
{
private const int STD_INPUT_HANDL E = -10;
private const int STD_OUTPUT_HAND LE = -11;
private const int STD_ERROR_HANDL E = -12;

private const ushort KEY_EVENT = 1;
private const ushort MOUSE_EVENT = 2;
private const ushort WINDOW_BUFFER_S IZE_EVENT = 4;
private const ushort MENU_EVENT = 8;
private const ushort FOCUS_EVENT = 16;
private const byte EMPTY = 32;

private IntPtr hConsoleHandle;
private COORD ConsoleOutputLo cation;
private CONSOLE_SCREEN_ BUFFER_INFO ConsoleInfo;
private int OriginalColors;

[StructLayout(La youtKind.Sequen tial)]
struct COORD
{
public short x;
public short y;
}

[StructLayout(La youtKind.Sequen tial)]
struct SMALL_RECT
{
public short Left;
public short Top;
public short Right;
public short Bottom;
}

[StructLayout(La youtKind.Sequen tial)]
struct CONSOLE_SCREEN_ BUFFER_INFO
{
public COORD dwSize;
public COORD dwCursorPositio n;
public int wAttributes;
public SMALL_RECT srWindow;
public COORD dwMaximumWindow Size;
}

// Key press event information
struct KEY_EVENT_RECOR D
{
public bool bKeyDown;
public ushort wRepeatCount;
public ushort wVirtualKeyCode ;
public ushort wVirtualScanCod e;
public byte AsciiChar; // we'll only process ASCII
public uint dwControlKeySta te;
}

// Information about the console input
struct INPUT_RECORD
{
public ushort EventType;
public KEY_EVENT_RECOR D KeyEvent;
};

[DllImport("kern el32.dll")]
private static extern IntPtr GetStdHandle(in t nStdHandle);

[DllImport("kern el32.dll")]
private static extern bool FillConsoleOutp utCharacter(Int Ptr
hConsoleHandle, byte cCharacter, int nLength, COORD dwWriteCoord, ref int
lpNumberOfChars Written);

[DllImport("kern el32.dll")]
private static extern bool GetConsoleScree nBufferInfo(Int Ptr
hConsoleHandle, ref CONSOLE_SCREEN_ BUFFER_INFO lpConsoleScreen BufferInfo);

[DllImport("kern el32.dll")]
private static extern bool SetConsoleCurso rPosition(IntPt r
hConsoleOutput, COORD dwCursorPositio n);

[DllImport("kern el32.dll")]
private static extern bool SetConsoleMode( IntPtr hConsoleHandle, uint
mode);

[DllImport("kern el32.dll")]
private static extern bool GetConsoleMode( IntPtr hConsoleHandle, out
uint mode);

[DllImport("kern el32.dll")]
private static extern bool ReadConsoleInpu tA(IntPtr hConsoleHandle, out
INPUT_RECORD rec, uint len, out uint c);

[DllImport("kern el32.dll")]
private static extern bool SetConsoleTextA ttribute(IntPtr
hConsoleOutput, int Attributes );

public enum Foreground
{
Blue = 0x00000001,
Green = 0x00000002,
Red = 0x00000004,
Intensity = 0x00000008
}

public enum Background
{
Blue = 0x00000010,
Green = 0x00000020,
Red = 0x00000040,
Intensity = 0x00000080
}

public ConsoleExt()
{
ConsoleInfo = new CONSOLE_SCREEN_ BUFFER_INFO();
ConsoleOutputLo cation = new COORD();
hConsoleHandle = GetStdHandle(ST D_OUTPUT_HANDLE );
GetConsoleScree nBufferInfo(hCo nsoleHandle, ref ConsoleInfo);
OriginalColors = ConsoleInfo.wAt tributes;
}

/// <summary>
/// Clear the Console window
/// </summary>
public void ClearScreen()
{
int hWrittenChars = 0;
ConsoleOutputLo cation.x = 0;
ConsoleOutputLo cation.y = 0;
FillConsoleOutp utCharacter(hCo nsoleHandle, EMPTY, ConsoleInfo.dwS ize.x
* ConsoleInfo.dwS ize.y, ConsoleOutputLo cation, ref hWrittenChars);
SetConsoleCurso rPosition(hCons oleHandle, ConsoleOutputLo cation);
}

/// <summary>
/// Get a single character from the console
/// </summary>
/// <returns>Key that has been pressed</returns>
public int ReadKey()
{
int ch = 0;
IntPtr stdin = GetStdHandle(ST D_INPUT_HANDLE) ;

uint oldstate;

// Save the existing mode
GetConsoleMode( stdin, out oldstate);

// Set the mode to character input
SetConsoleMode( stdin, 0);

// Read the console input until we get a single character
while(true)
{
INPUT_RECORD rec;
rec.EventType = 0;
rec.KeyEvent.bK eyDown = false;
rec.KeyEvent.wR epeatCount = rec.KeyEvent.wV irtualKeyCode =
rec.KeyEvent.wV irtualScanCode = 0;
rec.KeyEvent.As ciiChar = 0;
rec.KeyEvent.dw ControlKeyState = 0;

uint NumRead;

// Read the next console event
if (!ReadConsoleIn putA(stdin, out rec, 1, out NumRead))
{
// A problem has occurred, treat it as EOF
ch = -1;
break;
}

// Check that a button was pressed
if (((rec.EventTyp e & KEY_EVENT) > 0) && rec.KeyEvent.bK eyDown)
{
if ((ch = rec.KeyEvent.As ciiChar) > 0)
{
break;
}
}
}

// Restore the old console mode
SetConsoleMode( stdin, oldstate);

// Return the character
return ch;
}

/// <summary>
/// Set the text color
/// </summary>
/// <param name="color"></param>
public void TextColor(int color)
{
SetConsoleTextA ttribute(hConso leHandle, color);
}

/// <summary>
/// Reset the text color back to normal
/// </summary>
public void ResetColor()
{
SetConsoleTextA ttribute(hConso leHandle, OriginalColors) ;
}
}
}
----- End -----
Nov 17 '05 #1
5 6341
Could you send a small but complete program that demonstrates what is wrong?
Where exactly you get problems? What exception do you get and what do you do
before you get it?
Nov 17 '05 #2
Um, he did send us a complete code sample.
I can see the green background isn't cleared. Looking into it.
--
Happy coding!
Morten Wennevik [C# MVP]
Nov 17 '05 #3
Well, the documentations for FillConsoleOutp utCharacter remarks that attributes will not be changed. You can see this if you use a character instead of EMPTY. The green and blue foreground color is retained as well.

To overcome this I suggest you write something to the entire screen using the original color.
For instance, in your ClearScreen method you could do

public void ClearScreen()
{
ConsoleOutputLo cation.x = 0;
ConsoleOutputLo cation.y = 0;
int bufferLength = ConsoleInfo.dwS ize.x * ConsoleInfo.dwS ize.y;

SetConsoleCurso rPosition(hCons oleHandle, ConsoleOutputLo cation);
Console.Write(n ew char[bufferLength]);
SetConsoleCurso rPosition(hCons oleHandle, ConsoleOutputLo cation);
}

--
Happy coding!
Morten Wennevik [C# MVP]
Nov 17 '05 #4
Hi Morten.
That did not work as I do not have a reference to the console window.
However I spotted an old C++ article on msdn at
http://msdn.microsoft.com/library/en...the_screen.asp
so I just implemented FillConsoleOutp utAttribute to give

public void ClearScreen()
{
int hWrittenChars = 0;
ConsoleOutputLo cation.x = 0;
ConsoleOutputLo cation.y = 0;
FillConsoleOutp utCharacter(hCo nsoleHandle, EMPTY, ConsoleInfo.dwS ize.x *
ConsoleInfo.dwS ize.y, ConsoleOutputLo cation, ref hWrittenChars);
FillConsoleOutp utAttribute(hCo nsoleHandle, 0, ConsoleInfo.dwS ize.x *
ConsoleInfo.dwS ize.y, ConsoleOutputLo cation, ref hWrittenChars);
SetConsoleCurso rPosition(hCons oleHandle, ConsoleOutputLo cation);
}

This works a treat.

Thanks for trying.

Publicjoe

"Morten Wennevik" <Mo************ @hotmail.com> wrote in message
news:op.sqcrwvt 8klbvpo@stone.. .
Well, the documentations for FillConsoleOutp utCharacter remarks that attributes will not be changed. You can see this if you use a character
instead of EMPTY. The green and blue foreground color is retained as well.
To overcome this I suggest you write something to the entire screen using the original color. For instance, in your ClearScreen method you could do

public void ClearScreen()
{
ConsoleOutputLo cation.x = 0;
ConsoleOutputLo cation.y = 0;
int bufferLength = ConsoleInfo.dwS ize.x * ConsoleInfo.dwS ize.y;

SetConsoleCurso rPosition(hCons oleHandle, ConsoleOutputLo cation);
Console.Write(n ew char[bufferLength]);
SetConsoleCurso rPosition(hCons oleHandle, ConsoleOutputLo cation);
}

--
Happy coding!
Morten Wennevik [C# MVP]

Nov 17 '05 #5
Thank you for posting the solution. Since FillConsoleOutp utCharacter does not reset attributes calling FillConsoleOutp utAttribute would indeed be the logical thing to call :)

(Note to self: study the documents closer before giving an answer!)
On Fri, 06 May 2005 15:18:50 +0200, Publicjoe <mi**@publicjoe .co.uk> wrote:
Hi Morten.
That did not work as I do not have a reference to the console window.
However I spotted an old C++ article on msdn at
http://msdn.microsoft.com/library/en...the_screen.asp
so I just implemented FillConsoleOutp utAttribute to give

public void ClearScreen()
{
int hWrittenChars = 0;
ConsoleOutputLo cation.x = 0;
ConsoleOutputLo cation.y = 0;
FillConsoleOutp utCharacter(hCo nsoleHandle, EMPTY, ConsoleInfo.dwS ize.x *
ConsoleInfo.dwS ize.y, ConsoleOutputLo cation, ref hWrittenChars);
FillConsoleOutp utAttribute(hCo nsoleHandle, 0, ConsoleInfo.dwS ize.x *
ConsoleInfo.dwS ize.y, ConsoleOutputLo cation, ref hWrittenChars);
SetConsoleCurso rPosition(hCons oleHandle, ConsoleOutputLo cation);
}

This works a treat.

Thanks for trying.

Publicjoe

"Morten Wennevik" <Mo************ @hotmail.com> wrote in message
news:op.sqcrwvt 8klbvpo@stone.. .
Well, the documentations for FillConsoleOutp utCharacter remarks that

attributes will not be changed. You can see this if you use a character
instead of EMPTY. The green and blue foreground color is retained as well.

To overcome this I suggest you write something to the entire screen using

the original color.
For instance, in your ClearScreen method you could do

public void ClearScreen()
{
ConsoleOutputLo cation.x = 0;
ConsoleOutputLo cation.y = 0;
int bufferLength = ConsoleInfo.dwS ize.x * ConsoleInfo.dwS ize.y;

SetConsoleCurso rPosition(hCons oleHandle, ConsoleOutputLo cation);
Console.Write(n ew char[bufferLength]);
SetConsoleCurso rPosition(hCons oleHandle, ConsoleOutputLo cation);
}

--
Happy coding!
Morten Wennevik [C# MVP]



--
Happy coding!
Morten Wennevik [C# MVP]
Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

43
12151
by: Dom | last post by:
can someone please help me display text in the console cout << "Testing"; in a different colour to the default one
6
5235
by: Louise | last post by:
Hi I have written an HTML pages which does not have any colour specifying tags as far I know. When I view this in an Microsoft internet explorer browser it appears with a white background and black text but when I change Windows start menu->settings->control panel ->display -> appearance and change scheme to 'High Contrast Black' the background in the browser changes to black and the text to white. I understand that the windows scheme...
1
5385
by: Oz | last post by:
This is long. Bear with me, as I will really go through all the convoluted stuff that shows there is a problem with streams (at least when used to redirect stdout). The basic idea is that my application (VB.NET) will start a process, redirect its stdout and capture that process' output, displaying it in a window. I've written a component for this, and a test application for the component. It allows me to specify a command to execute,...
0
1010
by: Publicjoe | last post by:
I am working on a little app which uses colour in the console window. I have created a class to extend the console functionality but the ClearScreen method does not work correctly. I am enclosing a complete project (SharpDevelop) to show what happens. If anybody has an idea of how to fix this, please let me know. Yes I am aware that this is all in .Net 2. Thanks in advance.
11
2492
by: Hugh Janus | last post by:
OK, this is driving me crazy! As far as I can tell it should work. It compiles fine. I am saving the fore and back colour of a RTB to the registry like this: Srx.SetValue("ForeColour", Console.ForeColor.ToArgb.ToString) Srx.SetValue("BackColour", Console.BackColor.ToArgb.ToString) Then, I try to read the colours back in at runtime and change the
4
9467
by: gurdz | last post by:
Does anyone know how to change the colour of the text in the console in C??
6
3114
by: Fredmanglis | last post by:
I've been teaching myself the C++ Programming language. So far however, I have not come across any useful tutorials on how I can output coloured text, create drawings or graphics in C++. All I can create is a simple console based application. I would like to know if it's possible to do it using just the standard header files or do I have to get proprietary ones. If there's anyone with a suggestion or a good tutorial he/she knows of, please...
0
1594
by: Badino | last post by:
Hi, Can someone tell me what to put in this code so that if a user selects 0 (Black) then make the font white (0) as my default colour is black on my Excel spreadsheet. Private Type CHOOSECOLOUR lStructSize As Long hwndOwner As Long Hinstance As Long rgbResult As Long lpCustColors As String
2
1464
by: lamanvic | last post by:
i am trying to create a list of array with random numbers and use the colour sort to sort them to let the negative number on LHS zero in middle and positive number on RHS and print out the sorted array but it doesn't work and i have no idea what is wrong with it can some one please help me thanks using System; using System.Collections.Generic; using System.Text;
0
8766
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9291
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9217
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9158
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8160
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4535
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4799
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2698
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2171
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.