Running a C++ Console Program in full screen - c++

How to run a C++ Console Program in full screen ? , using VS2008

Just tested this with cl fullscreen.cpp :
#include <iostream>
#include <windows.h>
#pragma comment(lib, "user32")
int main()
{
::SendMessage(::GetConsoleWindow(), WM_SYSKEYDOWN, VK_RETURN, 0x20000000);
std::cout << "Hello world from full screen app!" << std::endl;
std::cin.get();
}
Unfortunatelly it had duplicated the text on the second monitor :)

try:
#include <iostream>
using namespace std;
int main(){
system("mode 650");
system("pause");
return 0;
}

#include <windows.h>
SetConsoleDisplayMode(GetStdHandle(STD_OUTPUT_HANDLE),CONSOLE_FULLSCREEN_MODE,0);

There are not a lot of video adapters around these days that still support this. Run cmd.exe and press Alt+Enter. If you get a message box that says "This system does not support fullscreen mode" then you're done. If it does switch to full screen then you can use SetConsoleDisplayMode() in your main() function. Of course, you don't know what your customer's machine is like, best not to pursue this.

That's what I'm using:
system("mode con COLS=700");
ShowWindow(GetConsoleWindow(),SW_MAXIMIZE);
SendMessage(GetConsoleWindow(),WM_SYSKEYDOWN,VK_RETURN,0x20000000);
It removes the scrollbar :D

For full screen windowed mode: ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);

Just a workaround: You could use some sort of earlier DOS video modi, for example...
asm
{
mov ax, 13h
push bp
int 10h
pop bp
}
...to have a resolution of 320x200 pixels.
But I'm not sure if this would work for a windows application... Probably not!

Just add this line (anywhere) before your output,
system("mode 650");
Such as,
#include<bits/stdc++.h>
using namespace std;
int main(){
system("mode 650");
cout<<"Hey, this words are shown in full screen console! "<<endl;
return 0;
}

Related

What can I replace with the sleep command in the Windows variant of ncurses?

#include <curses.h>
#include <unistd.h>
#include <iostream>
int main() {
initscr();
mvaddstr(10, 10, "Hello, world");
refresh();
sleep(4);
endwin();
std::cout << "DONE\n";
}
I'm working on a project and I need to take down the curses windows for a while just to write a path to directory in cmd and then let the curses windows come back. I found this code on this site and tried to use sleep command in the code but it didn't work.
So if anyone knew how to solve this please write it down here. Thnx :)
napms is the (portable) curses function to use instead of sleep

How to change the windows 10 wallpaper with C++?

I am looking to change the Windows desktop background wallpaper in C++ using the Windows API.
I have read the following posts on this topic:
How to change desktop background using VC++
SystemParametersInfo sets wallpaper completly black (using SPI_SETDESKWALLPAPER)
Problem:
When I execute the code, the desktop background changes to completely black like in the post above (yes, I did try the suggested fix in that post. No luck.)
Code:
#include <windows.h>
int main() {
std::string s = "C:\\picture.jpg";
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (PVOID*)s.c_str(), SPIF_SENDCHANGE);
return 0;
}
I have also tried just (void*) instead of (PVOID*) above and an L in front of the string. Nothing works so far.
SOLVED:
Changing SystemParametersInfo to SystemParametersInfoA (as suggested in the comment and answer) did the trick.
I believe you should use a wchar_t as input for SystemParametersInfo() instead of a string and also use SystemParametersInfoW().
The following code worked for me:
#include <windows.h>
#include <iostream>
int main() {
const wchar_t *path = L"C:\\image.png";
int result;
result = SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (void *)path, SPIF_UPDATEINIFILE);
std::cout << result;
return 0;
}
Where result should return true if it manages to change the background.

How to clear a specific line in the console window

I'm making a text based top down game in c++,every time I move my player I need to clear the whole console window with system("CLS") and after that print the whole world again. That process is really slow and inefficient. My question is whether there is any function to clear a certain line in the console window that will not affect the rest of the text? For example, look at the code.
Thanks :)
#include <iostream>
#include<string>
#include "windows.h"
using namespace std;
int main()
{
cout << "hello\n";
cout << "world\n";
//Output:
// hello
// world
//Wanted Output:
//
// world
system("pause");
return 0;
}
I expect text to be printed on the screen and then one line will be cleared without affecting the rest of the text
The win32-API includes a function called SetConsoleCurserPosition: https://learn.microsoft.com/en-us/windows/console/setconsolecursorposition.
I used this function a few years ago.

make sounds (beep) with c++

How to make the hardware beep sound with c++?
Print the special character ASCII BEL (code 7)
cout << '\a';
Source
If you're using Windows OS then there is a function called Beep()
#include <iostream>
#include <windows.h> // WinApi header
using namespace std;
int main()
{
Beep(523,500); // 523 hertz (C5) for 500 milliseconds
cin.get(); // wait
return 0;
}
Source: http://www.daniweb.com/forums/thread15252.html
For Linux based OS there is:
echo -e "\007" >/dev/tty10
And if you do not wish to use Beep() in windows you can do:
echo "^G"
Source: http://www.frank-buss.de/beep/index.html
There are a few OS-specific routines for beeping.
On a Unix-like OS, try the (n)curses beep() function. This is likely to be more portable than writing '\a' as others have suggested, although for most terminal emulators that will probably work.
In some *BSDs there is a PC speaker device. Reading the driver source, the SPKRTONE ioctl seems to correspond to the raw hardware interface, but there also seems to be a high-level language built around write()-ing strings to the driver, described in the manpage.
It looks like Linux has a similar driver (see this article for example; there is also some example code on this page if you scroll down a bit.).
In Windows there is a function called Beep().
alternatively in c or c++ after including stdio.h
char d=(char)(7);
printf("%c\n",d);
(char)7 is called the bell character.
You could use conditional compilation:
#ifdef WINDOWS
#include <Windows.h>
void beep() {
Beep(440, 1000);
}
#elif LINUX
#include <stdio.h>
void beep() {
system("echo -e "\007" >/dev/tty10");
}
#else
#include <stdio.h>
void beep() {
cout << "\a" << flush;
}
#endif
std::cout << '\7';
Here's one way:
cout << '\a';
From C++ Character Constants:
Alert: \a
#include<iostream>
#include<conio.h>
#include<windows.h>
using namespace std;
int main()
{
Beep(1568, 200);
Beep(1568, 200);
Beep(1568, 200);
Beep(1245, 1000);
Beep(1397, 200);
Beep(1397, 200);
Beep(1397, 200);
Beep(1175, 1000);
cout<<endl;
_getch()
return 0
}
I tried most things here, none worked on my Ubuntu VM.
Here is a quick hack (credits goes here):
#include <iostream>
int main() {
system("(speaker-test -t sine -f 1000)& pid=$!; sleep 1.0s; kill -9 $pid");
}
It will basically use system's speaker-test to produce the sound. This will not terminate quickly though, so the command runs it in background (the & part), then captures its process id (the pid=$1 part), sleeps for a certain amount that you can change (the sleep 1.0s part) and then it kills that process (the kill -9 $pid part).
sine is the sound produced. You can change it to pink or to a wav file.
Easiest way is probbaly just to print a ^G ascii bell
The ASCII bell character might be what you are looking for. Number 7 in this table.
cout << "\a";
In Xcode, After compiling, you have to run the executable by hand to hear the beep.

Is there a decent wait function in C++?

One of the first things I learned in C++ was that
#include <iostream>
int main()
{
std::cout<<"Hello, World!\n";
return 0;
}
would simply appear and disappear extremely quickly without pause. To prevent this, I had to go to notepad, and save
helloworld.exe
pause
ase
helloworld.bat
This got tedious when I needed to create a bunch of small test programs, and eventually I simply put while(true); at the end on most of my test programs, just so I could see the results. Is there a better wait function I can use?
you can require the user to hit enter before closing the program... something like this works.
#include <iostream>
int main()
{
std::cout << "Hello, World\n";
std::cin.ignore();
return 0;
}
The cin reads in user input, and the .ignore() function of cin tells the program to just ignore the input. The program will continue once the user hits enter.
Link
Please note that the code above was tested on Code::Blocks 12.11 and Visual Studio 2012
on Windows 7.
For forcing your programme stop or wait, you have several options :
sleep(unsigned int)
The value has to be a positive integer in millisecond.
That means that if you want your programme wait for 2 seconds, enter 2000.
Here's an example :
#include <iostream> //for using cout
#include <stdlib.h> //for using the function sleep
using namespace std; //for using cout
int main(void)
{
cout << "test" << endl;
sleep(5000); //make the programme waiting for 5 seconds
cout << "test" << endl;
sleep(2000); // wait for 2 seconds before closing
return 0;
}
If you wait too long, that probably means the parameter is in seconds. So change it to this:
sleep(5);
For those who get error message or problem using sleep try to replace it by _sleep or Sleep especially on Code::Bloks.
And if you still getting problems, try to add of one this library on the beginning of the code.
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <dos.h>
#include <windows.h>
system("PAUSE")
A simple "Hello world" programme on windows console application would probably close before you can see anything. That the case where you can use system("Pause").
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
system("PAUSE");
return 0;
}
If you get the message "error: 'system' was not declared in this scope" just add
the following line at the biggining of the code :
#include <cstdlib>
cin.ignore()
The same result can be reached by using cin.ignore() :
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.ignore();
return 0;
}
cin.get()
example :
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.get();
return 0;
}
getch()
Just don't forget to add the library conio.h :
#include <iostream>
#include <conio.h> //for using the function getch()
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
getch();
return 0;
}
You can have message telling you to use _getch() insted of getch
Lots of people have suggested POSIX sleep, Windows Sleep, Windows system("pause"), C++ cin.get()… there's even a DOS getch() in there, from roughly the late 1920s.
Please don't do any of these.
None of these solutions would pass code review in my team. That means, if you submitted this code for inclusion in our products, your commit would be blocked and you would be told to go and find another solution. (One might argue that things aren't so serious when you're just a hobbyist playing around, but I propose that developing good habits in your pet projects is what will make you a valued professional in a business organisation, and keep you hired.)
Keeping the console window open so you can read the output of your program is not the responsibility of your program! When you add a wait/sleep/block to the end of your program, you are violating the single responsibility principle, creating a massive abstraction leak, and obliterating the re-usability/chainability of your program. It no longer takes input and gives output — it blocks for transient usage reasons. This is very non-good.
Instead, you should configure your environment to keep the prompt open after your program has finished its work. Your Batch script wrapper is a good approach! I can see how it would be annoying to have to keep manually updating, and you can't invoke it from your IDE. You could make the script take the path to the program to execute as a parameter, and configure your IDE to invoke it instead of your program directly.
An interim, quick-start approach would be to change your IDE's run command from cmd.exe <myprogram> or <myprogram>, to cmd.exe /K <myprogram>. The /K switch to cmd.exe makes the prompt stay open after the program at the given path has terminated. This is going to be slightly more annoying than your Batch script solution, because now you have to type exit or click on the red 'X' when you're done reading your program's output, rather than just smacking the space bar.
I assume usage of an IDE, because otherwise you're already invoking from a command prompt, and this would not be a problem in the first place. Furthermore, I assume the use of Windows (based on detail given in the question), but this answer applies to any platform… which is, incidentally, half the point.
The appearance and disappearance of a window for displaying text is a feature of how you are running the program, not of C++.
Run in a persistent command line environment, or include windowing support in your program, or use sleep or wait on input as shown in other answers.
the equivalent to the batch program would be
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
std::cin.get();
return 0;
}
The additional line does exactly what PAUSE does, waits for a single character input
There is a C++11 way of doing it. It is quite simple, and I believe it is portable. Of course, as Lightness Races in Orbit pointed out, you should not do this in order to be able to see an Hello World in your terminal, but there exist some good reason to use a wait function. Without further ado,
#include <chrono> // std::chrono::microseconds
#include <thread> // std::this_thread::sleep_for
std::this_thread::sleep_for(std::chrono::microseconds{});
More details are available here. See also sleep_until.
Actually, contrary to the other answers, I believe that OP's solution is the one that is most elegant.
Here's what you gain by using an external .bat wrapper:
The application obviously waits for user input, so it already does what you want.
You don't clutter the code with awkward calls. Who should wait? main()?
You don't need to deal with cross platform issues - see how many people suggested system("pause") here.
Without this, to test your executable in automatic way in black box testing model, you need to simulate the enter keypress (unless you do things mentioned in the footnote).
Perhaps most importantly - should any user want to run your application through terminal (cmd.exe on Windows platform), they don't want to wait, since they'll see the output anyway. With the .bat wrapper technique, they can decide whether to run the .bat (or .sh) wrapper, or run the executable directly.
Focusing on the last two points - with any other technique, I'd expect the program to offer at least --no-wait switch so that I, as the user, can use the application with all sort of operations such as piping the output, chaining it with other programs etc. These are part of normal CLI workflow, and adding waiting at the end when you're already inside a terminal just gets in the way and destroys user experience.
For these reasons, IMO .bat solution is the nicest here.
What you have can be written easier.
Instead of:
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
return 0;
}
write
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
system("PAUSE");
return 0;
}
The system function executes anything you give it as if it was written in the command prompt. It suspends execution of your program while the command is executing so you can do anything with it, you can even compile programs from your cpp program.
Syntax:
void sleep(unsigned seconds);
sleep() suspends execution for an interval (seconds).
With a call to sleep, the current program is suspended from execution for the number of seconds specified by the argument seconds. The interval is accurate only to the nearest hundredth of a second or to the accuracy of the operating system clock, whichever is less accurate.
This example should make it clear:
#include <dos.h>
#include <stdio.h>
#include <conio.h>
int main()
{
printf("Message 1\n");
sleep(2); //Parameter in sleep is in seconds
printf("Message 2 a two seconds after Message 1");
return 0;
}
Remember you have to #include dos.h
EDIT:
You could also use winAPI.
VOID WINAPI Sleep(
DWORD dwMilliseconds
);
Sleep Function(Windows)
Just a note,the parameter in the function provided by winapi is in milliseconds ,so the sleep line at the code snippet above would look like this "Sleep(2000);"
getchar() provides a simplistic answer (waits for keyboard input).
Call Sleep(milliseconds) to sleep before exit.
Sleep function (MSDN)
You can use sleep() or usleep().
// Wait 5 seconds
sleep( 5 );
Well, this is an old post but I will just contribute to the question -- someone may find it useful later:
adding 'cin.get();' function just before the return of the main() seems to always stop the program from exiting before printing the results: see sample code below:
int main(){
string fname, lname;
//ask user to enter name first and last name
cout << "Please enter your first name: ";
cin >> fname;
cout << "Please enter your last name: ";
cin >> lname;
cout << "\n\n\n\nyour first name is: " << fname << "\nyour last name is: "
<< lname <<endl;
//stop program from exiting before printing results on the screen
cin.get();
return 0;
}
Before the return statement in you main, insert this code:
system("pause");
This will hold the console until you hit a key.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
cout << "Please enter your first name followed by a newline\n";
cin >> s;
cout << "Hello, " << s << '\n';
system("pause");
return 0; // this return statement isn't necessary
}
The second thing to learn (one would argue that this should be the first) is the command line interface of your OS and compiler/linker flags and switches.