//***************************************************************
// From the book "Win32 System Services: The Heart of Windows 98
// and Windows 2000"
// by Marshall Brain
// Published by Prentice Hall
//
// Copyright 1995, by Prentice Hall.
//
// This code demonstrates how to handle console output buffers
//***************************************************************

// 2buff.cpp

#include <windows.h>
#include <iostream.h>
#include <string.h>

void ErrorHandler(char *s, DWORD err)
{
	cout << s << endl;
	cout << "Error number: " << err << endl;
	ExitProcess(err);
}

void ShowBuffers(HANDLE consoleStdin,
	HANDLE consoleStdout, HANDLE newBuffer)
{
	char buffer[1000];
	DWORD numRead, numWrite;
	BOOL flag=TRUE;
	int x;

	for (x=0; x<10; x++)
	{
		WriteFile(consoleStdout, "Black\n", 6,
			&numWrite, 0);
 		WriteFile(newBuffer, "White\n", 6, &numWrite,
			0);
	}
	do
	{
		ReadFile(consoleStdin, buffer, 1000,
			&numRead, 0);
		if (flag)
			SetConsoleActiveScreenBuffer(newBuffer);
		else
			SetConsoleActiveScreenBuffer(
				consoleStdout);
		flag = !flag;
		WriteFile(consoleStdout, buffer, numRead,
			&numWrite, 0);
		
	} while  (strncmp(buffer, "quit", 4) != 0);
}

VOID main(void)
{
	HANDLE consoleStdout, consoleStdin;
	HANDLE newBuffer;

	// Get handles for standard in and out
	consoleStdin = GetStdHandle(STD_INPUT_HANDLE);
	consoleStdout = GetStdHandle(STD_OUTPUT_HANDLE);
	// they must be invalid if equal
	if (consoleStdin == consoleStdout) 
		ErrorHandler("In GetStdHandle",
			GetLastError());

	// Create second buffer
	newBuffer = CreateConsoleScreenBuffer(
		GENERIC_READ | GENERIC_WRITE,
		0, 0, CONSOLE_TEXTMODE_BUFFER, 0);

	// Show the two different buffers
	ShowBuffers(consoleStdin, consoleStdout,
		newBuffer);
}
