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

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.

Related

'Specific' Double buffering with this code?

For this code I am trying to implement double buffering so that it does not blink when updating the std::cout on my console window in windows 10. What is the best way to implement this into my current code? I am looking at some Microsoft documentation but I can't figure out a way to merge it so to speak?
void ClearScreen()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
homeCoords.X = 0;
homeCoords.Y = 0;
hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
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);
}
The basic idea is to call CreateConsoleScreenBuffer to create an off-screen buffer. Then clear/fill it as needed by passing the handle to that screen buffer when you do your calls to FillConsoleOutputCharacter, FillConsoleOutputAttribute, etc. When it's ready for the user to view, call SetConsoleActiveScreenBuffer to make it the active buffer for the console.
Note that in most cases you won't want to create a new screen buffer every time you clear the screen--rather you'll probably want to create two screen buffers when you start your program, and alternate between the two as you write and display output.

How to stop C/C++ program from checking keyboard when not active / in focus

I'm getting use to the basics of game programming and design. I'm currently trying to practice with using the command line to render images for a platformer by looping the screen output. I just want to make a few simple projects, e.g clock, tetris, cellular automata(looking forward to Game of Life ¯\_(ツ)_/¯ ), etc before using any advanced libraries or going into something like Unity®.
I used the GetAsyncKeyState(VK_key) function I found from various online resources to control the player with the arrow keys. This works, in fact a little too well. It has the unintended effect of controlling the player even when the program is in the background/ not in focus/ inactive.
So how do I CONSTANTLY get keyboard button states/input ONLY while program is in focus?
I've looked for various solutions, one of which was the first answer
here.
It required me knowing the process id of the program, to which I tried variants of (I only used one at a time):
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdbool.h>
#ifdef _WIN32
#include <Windows.h>
#define SLEEP(x) Sleep(x) // takes milliseconds(ms)
#else
#include <unistd.h>
#define SLEEP(x) usleep(x * 1000) // takes microseconds(μs)
#endif
void printInColour(char str[], unsigned short colour) {
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hcon, colour);
printf("%s", str);
SetConsoleTextAttribute(hcon, 7); // Set back to default.
}
bool key_pressed(int key) {
return (GetAsyncKeyState(key) != 0);
}
bool IsForegroundProcess()
{
HWND hwnd = GetForegroundWindow();
if (hwnd == NULL) return false;
DWORD foregroundPid;
if (GetWindowThreadProcessId(hwnd, &foregroundPid) == 0) return false;
//return true;
//return (foregroundPid == GetProcessId( GetStdHandle(STD_OUTPUT_HANDLE)));
//return ( foregroundPid == getpid() );
//return (foregroundPid == GetCurrentProcessId());
//return (foregroundPid == GetProcessIdOfThread(GetStdHandle(STD_OUTPUT_HANDLE) ));
return (foregroundPid == GetThreadId( GetStdHandle(STD_OUTPUT_HANDLE)));
}
void main() {
// ...
while(isRunning) {
//...
if (IsForegroundProcess())
printInConsole(">> Currently Active\n", 10); // Debug in green
else
printInConsole(">> Return to focus\n", 12); // ...and red
if (key_pressed(VK_UP) != 0) {/*...*/} // jump, etc
SLEEP(1000);
}
}
I edited the code to remove the actual game. The fix I tried constantly fails saying it's out of focus. I'm open to any suggestions of how to get key pressed info(but only when program is in focus/active). Also, any tips for a newcomer into this daunting world of creating games will be vastly appreciated.
Use FindWindow() in combination with GetForegroundWindow() or GetFocus()
HWND hMyWindow = FindWindow(NULL, L"MyWindowName");
HWND hFocusWindow = GetForegroundWindow();
//May also use:
//HWND hFocusWindow = GetFocus();
if (hMyWindow == hFocusWindow)
{
//do stuff
}

In Windows, Does SetCurrentConsoleFontEx change console's font size?

Other guys recommend the SetCurrentConsoleFontEx function but I don't know how to apply it to my project.
I want to change the font size of only some texts, not all texts.
Does SetCurrentConsoleFontEx() change the console's font size?
Or are there other ways to change it?
If there is, please show me the console function and a simple example.
Here is an example of using SetCurrentConsoleFontEx to change the console's font size. This affects the entire console window -- so like Joachim Pileborg already said, if you want mixed font sizes in a single console window, this won't help you.
#define _WIN32_WINNT 0x500
#include <Windows.h>
// PrintChars sends ASCII characters to console output
// for demonstration purposes.
// depends only on Win32 API
static void PrintChars() {
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD num_written;
static const char* cr_lf = "\r\n";
for(char c=' '; c<'\x7f'; ++c) {
WriteFile(hStdout, &c, 1, &num_written, NULL);
if(c % 16 == 15) WriteFile(hStdout, cr_lf, 2, &num_written, NULL);
}
WriteFile(hStdout, cr_lf, 2, &num_written, NULL);
}
// WaitEnter blocks execution until the user
// presses the enter key.
// depends only on Win32 API
static void WaitEnter() {
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
char buffer;
DWORD num_read;
do {
num_read = 0;
ReadFile(hStdin, &buffer, 1, &num_read, NULL);
} while(num_read && buffer != '\n');
}
int main() {
// Display some example characters
PrintChars();
// Wait for the user to see how the current font looks
WaitEnter();
// Get a handle to the current console screen buffer
HANDLE hcsb = CreateFileA("CONOUT$", GENERIC_WRITE | GENERIC_READ,
FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
CONSOLE_FONT_INFOEX cfi = {sizeof(cfi)};
// Populate cfi with the screen buffer's current font info
GetCurrentConsoleFontEx(hcsb, FALSE, &cfi);
// Modify the font size in cfi
cfi.dwFontSize.X *= 2;
cfi.dwFontSize.Y *= 2;
// Use cfi to set the screen buffer's new font
SetCurrentConsoleFontEx(hcsb, FALSE, &cfi);
// Wait for the user to see the difference before exiting
WaitEnter();
CloseHandle(hcsb);
}

c++ beginning to background

I make the bakcground running program.
this program is just simple [05:00 - reboot]..
I want hide the console windows..
Start from the beginning to background the console window
help.
#include "stdafx.h"
#include "stdio.h"
#include "windows.h"
#include "time.h"
#include "shellapi.h"
using namespace std;
int main()
{
while (true) {
time_t timer = time(NULL);
struct tm t;
localtime_s(&t, &timer);
int count_1 = 0;
if (t.tm_hour == 5) {
if (t.tm_min == 00) {
if (count_1 == 0) {
count_1 = 1;
WCHAR path[260];
GetModuleFileName(NULL, path, 260);
HWND console = FindWindow(L"ConsoleWindowClass", path);
if (IsWindow(console))
ShowWindow(console, SW_HIDE); // hides the window
system("shutdown -r");
if (IsWindow(console))
ShowWindow(console, SW_SHOW); // shows the window
}
}
}
}
}
Usually you would use the WinMain entry point instead of main.
But you need to tell your compiler that you're using WinMain which is compiler dependent.
By the way, there is a simpler way to hide the console window.
ShowWindow(GetConsoleWindow(), SW_HIDE);
But be aware that using this method the console is still being created and you might see it for a fraction of a second.

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