XCode windows.h and Displaying Colored Text - c++

In html5, you can do make colored text by doing this:
.foo
{
color: rgb(0,0,0);
}
I have recently started c++, and would like to display colored text to the user. I've Googled this and came up with stuff like this:
http://www.cplusplus.com/forum/beginner/5830/
Duoas' code snippet (shown below) looked interesting and I tried to run it on XCode.
#include <iostream>
#include <windows.h>
int main()
{
const WORD colors[] =
{
0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F,
0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6
};
HANDLE hstdin = GetStdHandle( STD_INPUT_HANDLE );
HANDLE hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
WORD index = 0;
// Remember how things were when we started
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo( hstdout, &csbi );
// Tell the user how to stop
SetConsoleTextAttribute( hstdout, 0xEC );
std::cout << "Press any key to quit.\n";
// Draw pretty colors until the user presses any key
while (WaitForSingleObject( hstdin, 100 ) == WAIT_TIMEOUT)
{
SetConsoleTextAttribute( hstdout, colors[ index ] );
std::cout << "\t\t\t\t Hello World \t\t\t\t" << std::endl;
if (++index > sizeof(colors)/sizeof(colors[0]))
index = 0;
}
FlushConsoleInputBuffer( hstdin );
// Keep users happy
SetConsoleTextAttribute( hstdout, csbi.wAttributes );
return 0;
}
However, the error I get is
2:21: fatal error: windows.h: No such file or directory
compilation terminated.
So here's my question:
Is there an alternative to windows.h in XCode?
If not, how can you display colors to the console?
(note: I am trying to make my hello world program display hello world in another color, rather than black)
Any help is appreciated.
Thanks!
EDIT:
Ok, thanks to duskwuff's answer, I know windows.h can only be run on windows. I have a PC, but it's not running on the compiler I am currently using. What compiler can I use to run the code sample?

The sample code you are trying to use is highly specific to the Windows console, and has no direct equivalent in macOS.
The Xcode console does not support colors.
If you are running your application in the macOS Terminal (not the Xcode console), you can use ncurses to display colors. Alternatively, you can use color code escapes directly.

Related

SetTextColor not changing command line text color

Since BGI is obsolete, and a lot of its source code seems to be missing from the original website, I've been meaning to design my own color engine that will affect lines individually. So far, the 16 colors that "SetConsoleTextAttribute ()" from windows.h can accept have been doing fine, but I've been meaning to use more colors (by using RGB instead of 0xbf) to upgrade the look of it and color my own ASCII art.
"SetTextColor ()" seems to be the route I want to go. I've set up a testing function to see if it works. Here's the snippet of code with the setup.
HDC hType; // Handle DC, save some work to reduce repetition
int initColor () // Initializes engine
{
hType = GetDC (GetConsoleWindow ());
printf ("String Hexadecimal\n");
testcolorR (RGB(255, 0, 0)); // Red
testcolorR (RGB(0, 255, 0)); // Green
testcolorR (RGB(0, 0, 255)); // Blue
getch (); // Pause to see results
return 0; // Exit success
}
// Take in RGB
void colortextR (COLORREF rgbcolor)
{
SetTextColor (hType, rgbcolor);
}
// Test RGB colors
int testcolorR (COLORREF color)
{
colortextR (color);
printf ("Hello %#x\n", color);
return 0;
}
However, on the command line, the color did not change and remained as the default light-gray, but this is the result.
String Hexadecimal
Hello 0xff
Hello 0xff00
Hello 0xff0000
Which means that the RGB color is being passed, but something else is causing this problem. I suspect the culprit is the GetConsoleWindow () function.
SetTextColor is a GUI function; it will not have the effect you want in a standard Windows console.
If your application will only be run on Windows 10 build 14392 or later, or on (most) non-Windows platforms such as Linux, then you can generally use virtual terminal sequences. Please note that even on supported versions of Windows, VT functionality must be explicitly enabled:
// error handling omitted for brevity; see GetLastError
HANDLE hOut = GetStdHandle( STD_OUTPUT_HANDLE );
if( hOut == INVALID_HANDLE_VALUE ) { return; }
DWORD dwMode = 0;
if( !GetConsoleMode( hOut, &dwMode ) ) { return; }
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if( !SetConsoleMode( hOut, dwMode ) ) { return; }
std::cout << "\x1b[91mRed\n"
<< "\x1b[92mGreen\n"
<< "\x1b[94mBlue\n"
<< "\x1b[38;5;221mArbitrary RGB color\n"
<< "\x1b[0mReset colors\n";
If your application needs to run on older versions of Windows, and the standard 16-color palette is sufficient, then something similar to the following will work (see SetConsoleTextAttribute and console screen buffer text attributes):
// error handling omitted for brevity; see GetLastError
HANDLE hOut = GetStdHandle( STD_OUTPUT_HANDLE );
if( hOut == INVALID_HANDLE_VALUE ) { return; }
// save current buffer information
CONSOLE_SCREEN_BUFFER_INFO sbInfo{ sizeof CONSOLE_SCREEN_BUFFER_INFO };
GetConsoleScreenBufferInfo( hOut, &sbInfo );
SetConsoleTextAttribute( hOut, FOREGROUND_RED | FOREGROUND_INTENSITY );
std::cout << "Red\n";
SetConsoleTextAttribute( hOut, FOREGROUND_GREEN | FOREGROUND_INTENSITY );
std::cout << "Green\n";
SetConsoleTextAttribute( hOut, FOREGROUND_BLUE | FOREGROUND_INTENSITY );
std::cout << "Blue\n";
SetConsoleTextAttribute( hOut, FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN );
std::cout << "Light Gray\n";
SetConsoleTextAttribute( hOut, sbInfo.wAttributes );
std::cout << "Reset colors\n";

How to find height of mozilla firefox full web page in mfc c++

i have done lot of work on it, but couldn't find the height of mozilla firefox full web page.
i use this code in all the way according to information given on the different sites, but couldn't find the ISimpleDOMNode object.
IServiceProvider *pServProv = NULL;
pAccessible->QueryInterface(IID_IServiceProvider, (void**)&pServProv);
ISimpleDOMNode *pSimpleDOMNode;
if (pServProv) {
const GUID refguid = {0x0c539790, 0x12e4, 0x11cf, 0xb6, 0x61,
0x00, 0xaa, 0x00, 0x4c, 0xd6, 0xd8};
HRESULT result = pServProv->QueryService(refguid, IID_ISimpleDOMNode,
(void**)&pSimpleDOMNode);
if (SUCCEEDED(hresult) && pSimpleDOMNode != NULL) {
/* This is a Mozilla node! Use special ISimpleDOMNode methods described in
ISimpleDOMNode.idl. */
}
}
plz, help me on this.
thanks.
Well, have you looked at the ISimpleDOMNode.idl file as it says in the comment?

c++ Program to take a screenshot

I am making a program that will click the printscreen key of the keyboard. The code I am using is the following:
INPUT myInput;
myInput.type = INPUT_KEYBOARD;
KEYBDINPUT keyboardInput;
keyboardInput.wScan = 0;
keyboardInput.dwFlags = 0;
keyboardInput.time = 0;
keyboardInput.dwExtraInfo = 0;
keyboardInput.wVk = VK_SNAPSHOT;
myInput.ki = keyboardInput;
SendInput(1, &myInput, sizeof(INPUT));//pressing the printscreen key
keyboardInput.dwFlags = KEYEVENTF_KEYUP;
myInput.ki = keyboardInput;
SendInput(1, &myInput, sizeof(INPUT));//releasing the printscreen key
for some reason the code doesn't work what so ever. If I go to paint and try to paist from clipboard, it will only past whatever printscreen I had done before I had used my program. Also my keyboard doesn't need me to press the "alt" with the print screen in order for it to work..
I had tryed to included the pressing of the Alt key beeeforee the pressing of the printscreen key, as well as the release of the Alt key afffftterr the releasing of the printscreen key, and the difference I got was that when I tried to past it on paint, I paist some kind of a full black screen... This was just a test I did to see if it makes a difference, but my actual keyboard takes screenshots with only the hit of the print screen button.
Any ideas on what I am doing wrong guys?
Edited:
just to let you guys know, the program does in fact compile. I have also added other code that saves the clipboard file to a directory, and I do save a file correctly if I manually hit the print screen button... but if I keep looping this code with the saving to a directory, the same picture of the manually obtained screenshot appears... so that is how I know for sure that there is a problem with the hitting of the printscreen button.
On the windows platform:
You have to follow a certain sequence of simulated key presses.
The code below is a simulates keybd_event() keyboard events and puts the captured screen into the clipboard.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
keybd_event(VK_MENU, 0, 0, 0); //Alt Press
keybd_event(VK_SNAPSHOT, 0, 0, 0); //PrntScrn Press
keybd_event(VK_SNAPSHOT, 0, KEYEVENTF_KEYUP, 0); //PrntScrn Release
keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0); //Alt Release
return 0;
}
That is code for taking a screenshot in BMP and to convert it to JPG:
void TakeScreenShot(const std::string& path)
{
//setting to the screen shot
keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
//handler of the bitmap that save the screen shot
HBITMAP hBitmap;
//I have to give for it time to make it work
Sleep(100);
//take the screen shot
OpenClipboard(NULL);
//save the screen shot in the bitmap handler
hBitmap = (HBITMAP)GetClipboardData(CF_BITMAP);
//relese the screen shot
CloseClipboard();
std::vector<BYTE> buf;
IStream *stream = NULL;
HRESULT hr = CreateStreamOnHGlobal(0, TRUE, &stream);
CImage image;
ULARGE_INTEGER liSize;
// screenshot to jpg and save to stream
image.Attach(hBitmap);
image.Save(stream, Gdiplus::ImageFormatJPEG);
IStream_Size(stream, &liSize);
DWORD len = liSize.LowPart;
IStream_Reset(stream);
buf.resize(len);
IStream_Read(stream, &buf[0], len);
stream->Release();
// put the imapge in the file
std::fstream fi;
fi.open(path, std::fstream::binary | std::fstream::out);
fi.write(reinterpret_cast<const char*>(&buf[0]), buf.size() * sizeof(BYTE));
fi.close();
}

Allegro 5 & C++ - Creating a fullscreen console?

All right, here's my main goal: get a fullscreen, non-windowed console program (that looks like the DOS operating system when you open it). I've defined ALLEGRO_USE_CONSOLE and all that stuff. Here's my full code to look at:
#define _WIN32_WINNT 0x0500
#define ALLEGRO_USE_CONSOLE
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include "include/allegro.h"
using namespace std;
void SetColor(unsigned short hColor) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), hColor);
}
void Dots() {
int i = 1;
while (i <= 3) {
cout << ".";
Sleep(750);
i++;
}
}
void ClearConsoleScreen() {
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
if (!FillConsoleOutputCharacter(
hStdOut,
(TCHAR) ' ',
cellCount,
homeCoords,
&count
)
) return;
/* Fill the entire buffer with the current colors and attributes */
if (!FillConsoleOutputAttribute(
hStdOut,
csbi.wAttributes,
cellCount,
homeCoords,
&count
)
) return;
/* Move the cursor home */
SetConsoleCursorPosition( hStdOut, homeCoords );
}
int main() {
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_DISPLAY_MODE disp_data;
al_init(); // I'm not checking the return value for simplicity.
al_get_display_mode(al_get_num_display_modes() - 1, &disp_data);
al_set_new_display_flags(ALLEGRO_FULLSCREEN);
display = al_create_display(disp_data.width, disp_data.height);
al_rest(3);
al_destroy_display(display);
}
So what exactly do I need to do to be able to make the console full screen (non-windowed & borderless) AND be able to use cout and such? I'm running Win7 as well.
ALLEGRO_USE_CONSOLE just tells Allegro that you're planning on running the program with with a console window; you still have to set the subsystem to "console" in your linker options. Allegro has nothing to do with creating the console window.
Now, if you just want to make the console fullscreen on windows, there's SetConsoleDisplayMode but that has nothing to do with Allegro. You can't use Allegro's drawing API because there's no Direct3D or OpenGL context to use.
Edit: It seems the above function no longer works on modern versions of windows...
Using a console is extremely platform specific, which is part of the reason why allegro_native_dialog exists. But there's no way to put that into a fullscreen mode.
If you want cross-platform functionality, you could create your own emulated console using Allegro's drawing API, but it would be a large undertaking.
Generally people who want a console application don't care exactly how it looks, only that the right data comes out for the data that you put in.

Clear Screen Command in C++

I want to clear the screen after user enters some numbers in C++. I'm programming in console application mode.
so how to do it? My OS is win7 and My IDE is CodeBlocks and the Compiler is MingW...
It depends of your OS,
If you use linux:
system("clear");
If you use windows:
system("cls");
but this make your application lees portable, it's preferable to do
cout << string(50, '\n');
this line will print lines to seem like the terminal was 'cleared'.
A good article about that problem:
http://www.cplusplus.com/articles/4z18T05o/
You can use the clrscr() defined in conio.h.
Ways to clear screen the output screen.
you can try system methods E.g. system("CLS");
link the conio.h in your compiler. I forgot how to do that. if you will use clear screen repeatedly put this function.
enter code here
void clrscr()
{
system("cls");
}
That's what Microsoft has to say about clearing a console:
#include <windows.h>
void cls( HANDLE hConsole )
{
COORD coordScreen = { 0, 0 }; // home for the cursor
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD dwConSize;
// Get the number of character cells in the current buffer.
if( !GetConsoleScreenBufferInfo( hConsole, &csbi ))
{
return;
}
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
// Fill the entire screen with blanks.
if( !FillConsoleOutputCharacter( hConsole, // Handle to console screen buffer
(TCHAR) ' ', // Character to write to the buffer
dwConSize, // Number of cells to write
coordScreen, // Coordinates of first cell
&cCharsWritten ))// Receive number of characters written
{
return;
}
// Get the current text attribute.
if( !GetConsoleScreenBufferInfo( hConsole, &csbi ))
{
return;
}
// Set the buffer's attributes accordingly.
if( !FillConsoleOutputAttribute( hConsole, // Handle to console screen buffer
csbi.wAttributes, // Character attributes to use
dwConSize, // Number of cells to set attribute
coordScreen, // Coordinates of first cell
&cCharsWritten )) // Receive number of characters written
{
return;
}
// Put the cursor at its home coordinates.
SetConsoleCursorPosition( hConsole, coordScreen );
}
int main()
{
HANDLE hStdout;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
cls(hStdout);
return 0;
}
system("cls");
Brilliant. So what happens if I replace the Windows cls with my own malicious cls? You've just given me control, thanks! This is what's called a back door, and you left it wide open by using an insecure technique.
Source: http://www.daniweb.com/software-development/cpp/threads/76934/how-do-i-clear-my-screen-in-c.
One method is to output '\f' (corresponding to the ASCII form feed character, code 12, which is used by line printers to eject a page, and recognized by some common terminals and emulators as a clear screen).
That won't work on Windows.
#ifdef _WIN32
/* windows hack */
#else
std::cout << '\f' std::flush;
#endif