c++ beginning to background - c++

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.

Related

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
}

Filtering/Parsing list produced from EnumWindows in C++

I am using the following code to get a list of windows running on my machine
#include <iostream>
#include <windows.h>
using namespace std;
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
TCHAR buffer[512];
SendMessage(hwnd, WM_GETTEXT, 512, (LPARAM)(void*)buffer);
wcout << buffer << endl;
return TRUE;
}
int main()
{
EnumWindows(EnumWindowsProc, NULL);
return 0;
}
I want to get a list of what is normally refered to as a Window - I say this because when running the above code I get a list of around 40 entries, most of these are not what I would call windows.
Here is an excerpt of the output produced by running the above script on my machine, out of the 5 entries only Microsoft Visual Studio is a Window
...
Task Switching
Microsoft Visual Studio
CiceroUIWndFrame
Battery Meter
Network Flyout
...
How can I go about filtering/parsing this data, as there is not anything to use as an identifier.
I would use EnumDesktopWindows to enumerate all top-level windows in your desktop; you may even use the IsWindowsVisible API during the enumeration process, to filter non-visible windows out.
This compilable C++ code works fine for me (note that here I showed how to pass some additional info to the enumeration proc, in this case using a pointer to a vector<wstring>, in which the window titles are stored for later processing):
#include <windows.h>
#include <iostream>
#include <string>
#include <vector>
using std::vector;
using std::wcout;
using std::wstring;
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
if (!IsWindowVisible(hwnd))
{
return TRUE;
}
wchar_t titleBuf[512];
if (GetWindowText(hwnd, titleBuf, _countof(titleBuf)) > 0)
{
auto pTitles = reinterpret_cast<vector<wstring>*>(lParam);
pTitles->push_back(titleBuf);
}
return TRUE;
}
int main()
{
vector<wstring> titles;
EnumDesktopWindows(nullptr, EnumWindowsProc, reinterpret_cast<LPARAM>(&titles));
for (const auto& s : titles)
{
wcout << s << L'\n';
}
}
Define what you call a Window and query the windows handle for the correct properties. Use GetWindowLong() with for example GWL_HWNDPARENT to test if there's no parent window or if the parent window is the desktop window. Additional test may be needed, e.g. you can use the (extended) window styles. See also here for additional ideas on usable tests.

Calling a member pointer to function that points to a C function within a windows procedure make app crash

I have this main.cpp code:
#include <windows.h>
#include <commctrl.h>
#include <process.h>
#include <stdio.h>
void click(){printf("button clicked\n");}
struct WindowData
{
void (*PF)();
WindowData():PF(NULL){}
};
LRESULT CALLBACK dialog_procedure(HWND h,UINT u,WPARAM w,LPARAM l)
{
WindowData *wp=(WindowData*)GetWindowLongPtr(h,GWL_USERDATA);
switch(u)
{
case WM_COMMAND:
if(LOWORD(w)==BN_CLICKED)
if(wp && wp->PF)wp->PF();
break;
}
return DefWindowProc(h,u,w,l);
}
int main()
{
WindowData * windowdata=new WindowData();
windowdata->PF=click; //bind function
HWND window=CreateWindow(WC_DIALOG,"App",WS_VISIBLE|WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,0,0,300,300,0,0,0,windowdata);
HWND button=CreateWindow(WC_BUTTON,"Click",WS_VISIBLE|WS_CHILD,0,0,100,30,0,0,0,0);
SetWindowLongPtr(window,GWL_WNDPROC,(LONG_PTR)dialog_procedure);
MSG msg;
while(GetMessage(&msg,NULL,0,0)>0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 1;
}
Now i build all with: c++ main.cpp -lcomctl32
Run the executable
but when i press the "Click" button, PF is never called...
calling windowdata->PF() after binding, works;
calling click() anywhere in dialog_procedure works;
calling wp->PF() anywhere in dialog_procedure make app crash;
where am I wrong?
Add this line to main function:
SetWindowLongPtr(window,GWL_USERDATA,(LONG_PTR)windowdata);

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.

C++ Win 32 API: Problem With Passing window SW_HIDE

I am attempting to hide a 3rd part window on bootup of our computers. I am using the following code.
#include<windows.h>
#include <stdio.h>
int main() {
char windowName[500];
HWND window = FindWindow("WindowClassAsReportedByWindowSpy++", NULL);
//GetWindowText(window, windowName, 63);
ShowWindow(firefox,SW_HIDE);
getchar();
return 0;
}
The only problem is the window will not hide. Any ideas on why this isn't working /how I could accomplish this differently.
Most likely your program calls FindWindow before the target window is created, and so doesn't find it.
You'll need to sleep and retry the find.
You probably want to do sanity checks to make sure FindWindow is not returning NULL. Even better, call FindWindow in a loop until it doesn't return NULL.
#include <windows.h>
#include <stdio.h>
static const wchar_t g_cszFirefoxClass[] = L"firefox";
int __cdecl wmain(__in int argc, __in_ecount_z_opt(argc) wchar_t* _wargv[], __in_z_opt __wenviron[])
{
UNREFERENCED_PARAMETER(argc);
UNREFERENCED_PARAMETER(_wargv);
UNREFERENCED_PARAMETER(__wenviron);
HWND hWnd;
do {
hWnd = FindWindow(g_cszFirefoxClass, NULL);
Sleep(100);
} while (hWnd == NULL);
wprintf(L"[-] Firefox found! [HWND = 0x%X]\n", hWnd);
if (ShowWindow(hWnd, SW_HIDE))
{
wprintf(L"[-] Successfully hid Firefox window!\n");
return EXIT_SUCCESS;
}
else
{
fwprintf(stderr, L"[x] Failed to hide Firefox window..\n");
return EXIT_FAILURE;
}
}