VS C++ application leaving background process open - c++

I've got a VS c++ project using SFML that I'm working on but every time i close the program it leaves a background process open after the project has been exited.image of task manager here
I know roughly why this is happening but haven't found any other articles online with this issue. This issue started popping up after i started closing the console window upon startup of my program. In an attempt to remedy this (since i no longer need the console window anyways) I've tried to convert the project to a windows application, but the problem is persisting, I'll include the code in my main, any help is appreciated.
#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <SFML/Graphics.hpp>
#include "gameStates/StateStack.h"
using namespace std;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
bool close = false;
StateStack game;
do
{
game.handleEvents();
game.update();
game.draw();
}while(!close);
return 0;
}

Related

My program doesn't put characters out on the screen

I have tried several things but none of them did work. Does someone know what the problem is? Here's my code:
#include <iostream>
#include <Windows.h>
#include <iomanip>
#include <fstream>
#include <stdio.h>
using namespace std;
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int CmdShow) {
cout << "Hello World" << endl;
return 0;
}
Thanks
If you are using visual studio, and create a Win32 application, it will not create a console so the output does not appear on any window. If you create a Win32 Console application, std::cout will be directed to the console window but you will need to use a standard main() program entry point.
To avoid creating a new project, modify your code as shown here:
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int CmdShow) {
AllocConsole();
AttachConsole(GetCurrentProcessId());
freopen("CONOUT$", "w", stdout);
cout << "Hello World" << endl;
return 0;
}
On Windows, there are two main types of programs:
Console applications for single textual input and output. These are typically started from the command line in a command prompt.
GUI applications which use windows, buttons, the mouse, touch, etc. These are typically started by choosing from the start menu or double-clicking on an icon.
(There are ways to have a single application work both ways, but that's almost certainly not what you're after.)
Your code is exhibiting indications of trying to be both. It has a wWinMain, which suggests it's a GUI application, but it does regular textual output using std::cout, which suggests it's a console application.
I think you want a console application, but you accidentally started by choosing a Win32 application in the Visual Studio New Project Wizard. To fix this without starting over:
First, get rid of the unnecessary includes, specifically, delete #include <windows.h>.
Next Change the wWinMain to a standard C++ main function, like this:
int main() {
cout << "Hello World" << endl;
return 0;
}
Finally, right-click on your project in the Solution Explorer, and choose Properties from the pop-up menu. At the top of the pop-up dialog, set Configuration to All Configurations. In the left side, expand Linker and choose System, then, on the right side, change the SubSystem field to Console (/SUBSYSTEM:CONSOLE). Click OK.
Now you should be able to rebuild your program and it'll work.
One word of warning: If you run it directly from Visual Studio, a new console window will appear and, in the blink of an eye, your program will complete and the new console window will disappear, which makes it hard to tell if you did the right thing.
If you start your program from a CMD prompt, you won't have that problem. If you want to run from the debugger, put a breakpoint on the return statement in your main function. That will halt the program in the debugger just before it ends, and you'll be able to see what's in the console window. Some people have the program ask for keyboard input right before it finishes, which gives the user a change to see what's in the console window before it vanishes.
It appears you have created a windows application rather than a console application.
A console application has a main function with signature:
int main(int argc, char ** argv);
A windows application has a main function with signature:
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int CmdShow);
The latter is intended for applications that actually create a window. You choose which to create using the wizard in Visual Studio when you go to create a new project (assuming you are using Visual Studio).
Use:
https://msdn.microsoft.com/en-us/library/ms235629.aspx
Also, it is possible your application is exiting before you see the output.
In this case, we can use a non-standard platform specific call to ::system("pause") to make it wait until you hit a key to continue.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <windows.h>
using namespace std;
int main(int argc, char ** argv)
{
cout << "Hello World" << endl;
system("pause");
return 0;
}
Alternativly, place a break point on the line where it says return 0; and use F5 to debug.

SetProcessDPIAware seems not to work under windows 10

I am trying to get the real screen resolution (in pixels) in a windows C++ app. When the windows dpi setting is changed, I get the virtual (adjusted) resolution instead of the real one. I have tried using SetProcessDPIAware, SetProcessDpiAwareness (with all three enumerated values as arguments) and a true setting in a manifest. In all three cases, the code works fine (i.e. shows the real resolution) in my windows 7 PC but not in a Win 10 one (here it ignores the DPI Aware setting and returns the adjusted resolution).
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <winuser.h>
#include <VersionHelpers.h>
#include <ShellScalingAPI.h>
#include <stdlib.h>
#include <stdio.h>
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
char *cBuffer2 ;
cBuffer2 = (char *)malloc(3000) ;
if (IsWindowsVistaOrGreater())
{
// SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE);
int result = SetProcessDPIAware();
sprintf(cBuffer2,"SetProcessDPIAware() result: [%i]\n",result) ;
int height = GetSystemMetrics(SM_CYSCREEN);
int width = GetSystemMetrics(SM_CXSCREEN);
sprintf(cBuffer2,"%s#1:\nHeight: [%i]\nwidth: [%i]\n",cBuffer2,height,width) ;
HWND hwnd = (HWND)atoi(lpCmdLine) ;
HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
MONITORINFO info;
info.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(monitor, &info);
int monitor_width = info.rcMonitor.right - info.rcMonitor.left;
int monitor_height = info.rcMonitor.bottom - info.rcMonitor.top;
sprintf(cBuffer2,"%s#2:\nHeight: [%i]\nwidth: [%i]\n",cBuffer2,monitor_height,monitor_width) ;
}
MessageBox(0,cBuffer2,"SHOWRES.EXE",MB_OK) ;
return 0 ;
}
The manifest I tried using is the following one:
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" >
<asmv3:application>
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
<dpiAware>true</dpiAware>
</asmv3:windowsSettings>
</asmv3:application>
</assembly>
Any ideas?
I finally found out what is happening, with the help of Jonathan Potter and Barmak Shemirani: Windows 10, unlike previous versions of windows, allows the user to change the dpi settings 'on the fly', without the need to log out and login again. I was running the tests on a win 10 machine which normally has standard (100%) settings. So I would change the setting to 150%, run the app and get the wrong results.
Jonathan and Barmak's answers indicated that there is something in the specific PC's settings, not in the program or win 10 in general, that was causing my problems. So I tried the following:
- changed DPI settings to 150%
- logged out
- logged in again
- ran the program
And I got the correct results (real screen resolution, vs adjusted one).
So it seems that in order for SetProcessDPIAware (and the related approaches: SetProcessDpiAwareness() and manifest with true) to work correctly, one has to log out and login again after changing the DPI setting and before running the program.
Thanks again, Jonathan and Barmak!

On release mode cout does not print anything

I have a very weird problem. I am working with visual studio in C++ and suddenly cout does not work on release mode (It worked until now) and on debug mode it works fine. I have no idea why thats happans. I have tried to delete some code And I deleted almost all my program (I have backup). Here is my code:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow )
{
AllocConsole();
cout<<"asdasd"<<endl;
cin.get();
return 1;
}
In debug mode the program wait for the user for pressing Enter. In release mode it doesn't. The window just close.
I think that it might be a problem in the setting of visual. Can it be?
iostreams require initialization that's normally carried out by the startup code for a console application -- but since you're using WinMain instead of main as your entry point, it's being linked as a Windows-mode application instead of a console-mode application, so that initialization isn't happening (dependably, anyway). Under some (poorly defined) circumstances, things work anyway, but it's undependable at best.
Unless you're feeling so masochistic that you're willing to do a lot of extra work just to make your code non-portable, write your code the standard way:
#include <iostream>
int main() {
std::cout<<"asdasd\n";
std::cin.get();
return 1;
}
Short, simple, and dependable are all good things. Portable is kind of nice too.

C++ WIN32: Running a program without a command prompt window

I have written a program which triggers a relay switch on a serial port. The relay is closed for 10ms, after which the program closes. However, the program insists on running in a small command prompt window. I would like the program to run without stealing focus; either by running in the background or, even better, without opening a window at all.
Here is the complete program:
#include <windows.h>
//Initialise Windows module
int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance,
LPSTR lpszArgument, int nFunsterStil)
{
//Define the serial port precedure
HANDLE hSerial;
//Open the port
hSerial = CreateFile("COM1",GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
//Switch on relay
EscapeCommFunction(hSerial, SETDTR);
//Wait 10ms
Sleep(10);
//Switch off relay
EscapeCommFunction(hSerial, CLRDTR);
//Close the port
CloseHandle(hSerial);
//End with error code 0
return 0;
}
What must I change in order to prevent it running in a window?
Try adding #pragma comment(linker, "/SUBSYSTEM:WINDOWS")
If that does not work try to hide the window manually:
HWND hWnd = GetConsoleWindow();
ShowWindow( hWnd, SW_HIDE );
What type of project did you create? If you selected console application, the compiler is doing it. Make an empty Win32 application with the above source. No window should be created. If it is, consider how you're launching the application (start, cmd /c, etc)

Create an Application without a Window

How would you program a C/C++ application that could run without opening a window or console?
When you write a WinMain program, you automatically get the /SUBSYSTEM option to be windows in the compiler. (Assuming you use Visual Studio). For any other compiler a similar option might be present but the flag name might be different.
This causes the compiler to create an entry in the executable file format (PE format) that marks the executable as a windows executable.
Once this information is present in the executable, the system loader that starts the program will treat your binary as a windows executable and not a console program and therefore it does not cause console windows to automatically open when it runs.
But a windows program need not create any windows if it need not want to, much like all those programs and services that you see running in the taskbar, but do not see any corresponding windows for them. This can also happen if you create a window but opt not to show it.
All you need to do, to achieve all this is,
#include <Windows.h>
int WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int cmdShow)
{
/* do your stuff here. If you return from this function the program ends */
}
The reason you require a WinMain itself is that once you mark the subsystem as Windows, the linker assumes that your entry point function (which is called after the program loads and the C Run TIme library initializes) will be WinMain and not main. If you do not provide a WinMain in such a program you will get an un-resolved symbol error during the linking process.
In windows:
#include <windows.h>
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
// <-- Program logic here
return 0;
}
Be sure to use the /SUBSYSTEM linker switch as mentioned by Adam Mitz.
On other platforms:
int main(int argc, char**argv)
{
// <-- Program logic here
return 0;
}
If you have a need to contiguously run your program without having console or window you might find useful deamon on *NIX or services on Windows, this .NET example if you need plain win32 just google a little bit for sample.
Since your question tagged as win32 i assume that services are more relevant for you.
This also processes messages:
#include <windows.h>
#include <stdio.h>
int CALLBACK WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
MSG msg;
DWORD curThreadId;
curThreadId = GetCurrentThreadId();
// Send messages to self:
PostThreadMessage(curThreadId, WM_USER, 1, 2);
PostThreadMessage(curThreadId, WM_USER+1, 3, 4);
PostThreadMessage(curThreadId, WM_USER+2, 5, 6);
PostThreadMessage(curThreadId, WM_USER+3, 7, 8);
PostThreadMessage(curThreadId, WM_QUIT, 9, 10);
while (GetMessage(&msg, NULL, 0, 0)) {
printf("message: %d; wParam: %d; lParam: %d\n", msg.message, msg.wParam, msg.lParam);
}
return (int) msg.wParam;
}
In Visual Studio Express 2010 after setting the subsystem to windows (as suggested by user17224), alternatively to changing the main to WinMain (as suggested by user17224 and Brian R. Bondy), one can set the entry function to main in properties, linker, advanced, entry point: just type main in the text box.
Use Visual Studio wizard to create the Win32 Application. But don't create the window i.e., you remove the window creation function.
Alternatively we can create Win Service application.
If you are using MSVC or Visual Studio just use the new Project Wizard and select the Console Application.