Page 1 of 1

DOS COnsole color changer function complete

Posted: Wed Apr 07, 2010 6:51 am
by dream_coder
Here is the code for the function I have been yakking on about for the last day in its completed glory. It is based loosely on the GameTutorials website code on changing text colour but I have modified it to suit my needs.

Code: Select all

void ColorString(string szText, WORD color);   //Function to change text colour.

void ColorString(string szText, WORD color)    //Function to change text colour.
{	
	
	HANDLE OutputH;	
	OutputH = GetStdHandle(STD_OUTPUT_HANDLE);
	
	//Need to read up on this code, learn abut pointers and shit
	CONSOLE_SCREEN_BUFFER_INFO *ConsoleInfo = new CONSOLE_SCREEN_BUFFER_INFO();
	GetConsoleScreenBufferInfo(OutputH, ConsoleInfo);
	WORD OriginalColors = ConsoleInfo->wAttributes;
	//--------------------------------	

	SetConsoleTextAttribute(OutputH, color);
	cout << szText;

	SetConsoleTextAttribute(OutputH, OriginalColors);
}


Basically if you want to change the text color, when you call the function szText is the string to pass in that you want to print in a different colour. The word color is the colour that you want it, for example FOREGROUND_RED, FOREGROUND_BLUE and FORGROUND_GREEN.

PS. This is not a copy of other peoples code, I have took there code and totally changed it.


ALso just done a little program to draw boxes in DOS using arrays. AInt sure why this would be useful, but took me a while to get my head around how to do it just using Height and Width.

Code: Select all

#include <iostream>
#include <windows.h>
using namespace std;


int main()
{
	int pause;

	char box[9][9];
	int intLength;
	int intHeight;

	int HeightLess;

	// Get Dimensions for box

	cout << "Please enter Length (max of 8): ";
	cin >> intLength;
	cout << endl;
	cout << "Please enter Width (max of 8): ";
	cin >> intHeight;

	//Clear the array
	for (int d = 1; d <=intHeight; d++)
	{
		for (int e = 1; e <=intLength; e++)
		{
			box[d][e] = ' ';
		}
		cout << endl;
	}
	
	//Clear Screen and draw box
	system("cls");

	for (int i = 1 ; i <= intLength; i++)
	{
		box[1][i] = '*';
		box[intHeight][i] ='*';

		box[i][1] = '*';
		box[i][intLength] = '*';
	}

	for (int x = 1; x <=intHeight; x++)
	{
		for (int y = 1; y <=intLength; y++)
		{
			cout << box[x][y];
		}
		cout << endl;
	}

	


	cin >> pause;
	return 0;
	



}

Re: DOS COnsole color changer function complete

Posted: Wed Apr 07, 2010 10:54 am
by Bakkon
You need to delete ConsoleInfo when you're done with it or else you'll have a memory leak.

Re: DOS COnsole color changer function complete

Posted: Wed Apr 07, 2010 11:13 am
by dream_coder
I shall look into that. Cheers