start a program without a console window (in background) - c

I want to start a simple program when windows start but I don't want to show the console output window associated with that program. Just to test, the program can be as simple as:
int main (int argc, char** argv)
{
while (1)
{
printf ("hello world...\n");
Sleep (10000);
}
return 0;
}
compiling it as: cl foo.c
I know how to start the program when windows is starting (putting in startup folder, creating registry etc), but I don't know how to hide the console output window that comes when the program is started.
While searching for this, I found that I can use start /B foo.exe. Is there any other method for doing this? some thing like "&" we use on unix.
My actual program is big and is written in C, so I can not use some other alternatives i found for c# (like WinMain) and java (like explained here).

This should work.
#include <windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdParam, int iCmdShow)
{
for (;;) {
//action here
}
return 0;
}

WinMain is not a C# entry point. C# uses a method of a static class; it is called Main by default, but can be configured to any static-class method.
In Windows, non-console C programs should define a WinMain. You can then link them using the linker's /subsystem:windows command-line option, invokable either directly or from CL.

One method is calling FreeConsole() as first thing in main. It will hide the console window, if any.

Unfortunately simply setting FreeConsole() as the first function in main allows the window to appear momentarily anyway. And FreeConsole removes the window so that if you wish to use it later( as in killing the process ) you have to make it appear on screen in a mode out of your control.
Windows allows Win32 programs to have only one of four contexts under Visual Studio: Window program with initial GUI window, Console program with initial Console window, DLL or Lib. Changing the subsystem to a non-Console choice from the project->Properties->System view only results in linking issues that block the build.
Here is what worked for me with only a little effort. Use Mike's approach above and choose Win32 Project with Window Application. Then delete everything in WinMain after the "Place code here" direction and delete all the called functions. Return true or 1, as you wish from WinMain. No window of any type will appear on launch.
And when you are ready to deal with a Console Window call AllocConsole() in your code and deal with its positioning and size as you see fit. The Console can be positioned off screen and slid into view if you wish; it only takes a few minutes to get the handle on the configuring functions. Start with Microsoft's 'Console Functions' in MSDN documents. Unfortunately, there is no book on how to use all the functions properly as there is for NCurses in Linux.

When you're creating your project create one with WinMain instead ( Win32 Project ). If you still want the console later use AllocConsole() and FreeConsole().

If the program would be eg procexp.exe you can do this out of the box :
cmd /c "start C:\Users\denni\OneDrive\_bin\_tools\ProcessExplorer\procexp.exe"

WinMain isn't unique to C#. It's possible to write GUI applications in C too. The WinMain function is the entry point, but nothing says you have to actually create a window. You could have WinMain do nothing more than call the first function of your program to get it started. Then you'd have your program running with no GUI window and no console window.
Of course, this also means no easy way to stop it, short of killing it from Task Manager.

Related

How to remove execution related text from output window of Code::Blocks

I am using Code::Blocks for programming in C. When I compile my program and execute it, the output window (i.e.. Windows Command prompt) displays some execution related text, these texts are not of use to me right now and dont want them to appear(see text below).
Hello, World!
Process returned 0 (0x0) execution time : 3.920 s
Press any key to continue.
I tried to change the settings in Code::Blocks but couldn't find any settings related to the output window and also I dont want the text "Press any key to continue" to appear. These texts appear only if I run the program through Code::Blocks and doesn't appear if I directly run the program.
Unfortunately, some things just cannot be changed, and that is one of them. There are some quirks used by some IDE's that just drive programmers crazy, but it can't be helped. There is a reason why it's there: the execution data can be used to find out whether the program worked properly (e.g. ended execution). You can use this data later when targeting execution time as one of the main focuses in coding the project. There may be other uses for it as you code more and more advanced projects.
It only appears when you execute your code from the compiler. It does not need getch() function to stop the screen.
But if you execute its .exe file directly, outside the compiler, you will notice that annoying message 'Process returned 0 (0x0) execution time : 3.920 s' doesn't show anymore. Moreover, you will need getch() function to stop the screen.
you may need to include stdio.h and then call getchar() before return 0
for example;
#include <iostream>
//add this library
#include <stdio.h>
using namespace std;
int main()
{
cout<<"I am a C++ programmer! "<<"Awesome!";
//add this line of code
getchar();
return 0;
}

opening an .exe after using Mingw

I followed the instructions in this video:(See Docs)
What happened is that I created a very basic program in C, here is the code:
#include <stdio.h>
int main()
{
printf("Hey Buddy!\n");
return 0;
}
I compiled it using Mingw and an .exe file was created. Here the problem begins...
When simply opening the file in windows, a cmd window that says "Hey Buddy!" opens and closes immediately.
When trying to run the .exe file using the command line, the same thing happens, but the command line window then becomes stuck and it is impossible to close it - only shutting off the computer can do it.
Your help would be very appreciated, and I am sorry if I am doing something dumb and not realizing it:)
Your program is fine. The main declaration is wrong. It should be
int main(void)
but the declaration in your question won't cause any problems. I'm just telling you this to set you off on the right path.
Of course when you double click on the executable, then a new console window appears and immediately disappears. The program prints a single line of text and returns immediately. That behaviour is as expected.
The problem with the console window that cannot be closed is not down to an error in your code, at least the code that is shown in the question cannot explain that. That is presumably an environmental problem with your machine and/or compiler installation. Or perhaps you just have not yet worked out how to close a console window.

How can I see an the output of my C programs using Dev-C++?

I'm looking to follow along with The C Programming Language (Second Addition) on a machine running Vista.
So far, I've found Dev-C++ the easiest IDE to do this in. However, I still have one problem. Whenever I run my compiled code, for example: a simple hello world program, it runs, but the console window just flickers on the screen, and I can't see the output.
How can I see an the output of my C programs using Dev-C++? I found a C++ specific solution, System("pause"), and a really ugly C solution, while looping fflush(stdout), but nothing nice and pretty.
I put a getchar() at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar, getch, or getc
In Windows when a process terminates, the OS closes the associated window. This happens with all programs (and is generally desirable behaviour), but people never cease to be surprised when it happens to the ones they write themselves.
I am being slightly harsh perhaps; many IDE's execute the user's process in a shell as a child process, so that it does not own the window so it won't close when the process terminates. Although this would be trivial, Dev-C++ does not do that.
Be aware that when Dev-C++ was popular, this question appeard at least twice a day on Dev-C++'s own forum on Sourceforge. For that reason the forum has a "Read First" thread that provides a suggested solution amongst solutions to many other common problems. You should read it here.
Note that Dev-C++ is somewhat old and no longer actively maintained. It suffers most significantly from an almost unusable and very limited debugger integration. Traffic on the Dev-C++ forum has been dropping off since the release of VC++ 2005 Express, and is now down to a two or three posts a week rather than the 10 or so a day it had in 2005. All this suggest that you should consider an alternative tool IMO.
Use #include conio.h
Then add getch(); before return 0;
The easiest thing to do is to run your program directly instead of through the IDE. Open a command prompt (Start->Run->Cmd.exe->Enter), cd to the folder where your project is, and run the program from there. That way, when the program exits, the prompt window sticks around and you can read all of the output.
Alternatively, you can also re-direct standard output to a file, but that's probably not what you are going for here.
For Dev-C++, the bits you need to add are:-
At the Beginning
#include <stdlib.h>
And at the point you want it to stop - i.e. before at the end of the program, but before the final }
system("PAUSE");
It will then ask you to "Press any key to continue..."
Add this to your header file #include
and then in the end add this line : getch();
You can open a command prompt (Start -> Run -> cmd, use the cd command to change directories) and call your program from there, or add a getchar() call at the end of the program, which will wait until you press Enter. In Windows, you can also use system("pause"), which will display a "Press enter to continue..." (or something like that) message.
Add a line getchar(); or system("pause"); before your return 0; in main function.
It will work for you.
;
It works...
#include <iostream>
using namespace std;
int main ()
{
int x,y; // (Or whatever variable you want you can)
your required process syntax type here then;
cout << result
(or your required output result statement); use without space in getchar and other syntax.
getchar();
}
Now you can save your file with .cpp extension and use ctrl + f 9 to compile and then use ctrl + f 10 to execute the program.
It will show you the output window and it will not vanish with a second Until you click enter to close the output window.
i think you should link your project in console mode
just press Ctrl+h and in General tab select console.
When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.
The use of line system("PAUSE") will fix that problem and also include the pre processor directory #include<stdlib.h>.
Well when you are writing a c program and want the output log to stay instead of flickering away you only need to import the stdlib.h header file and type "system("PAUSE");" at the place you want the output screen to halt.Look at the example here.The following simple c program prints the product of 5 and 6 i.e 30 to the output window and halts the output window.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
a=5;b=6;
c=a*b;
printf("%d",c);
system("PAUSE");
return 0;
}
Hope this helped.

Preventing console window from closing on Visual Studio C/C++ Console application

This is a probably an embarasing question as no doubt the answer is blindingly obvious.
I've used Visual Studio for years, but this is the first time I've done any 'Console Application' development.
When I run my application the console window pops up, the program output appears and then the window closes as the application exits.
Is there a way to either keep it open until I have checked the output, or view the results after the window has closed?
If you run without debugging (Ctrl+F5) then by default it prompts your to press return to close the window. If you want to use the debugger, you should put a breakpoint on the last line.
Right click on your project
Properties > Configuration Properties > Linker > System
Select Console (/SUBSYSTEM:CONSOLE) in SubSystem option or you can just type Console in the text field!
Now try it...it should work
Starting from Visual Studio 2017 (15.9.4) there is an option:
Tools->Options->Debugging->Automatically close the console
The corresponding fragment from the Visual Studio documentation:
Automatically close the console when debugging stops:
Tells Visual Studio to close the console at the end of a debugging session.
Here is a way for C/C++:
#include <stdlib.h>
#ifdef _WIN32
#define WINPAUSE system("pause")
#endif
Put this at the top of your program, and IF it is on a Windows system (#ifdef _WIN32), then it will create a macro called WINPAUSE. Whenever you want your program to pause, call WINPAUSE; and it will pause the program, using the DOS command. For other systems like Unix/Linux, the console should not quit on program exit anyway.
Goto Debug Menu->Press StartWithoutDebugging
If you're using .NET, put Console.ReadLine() before the end of the program.
It will wait for <ENTER>.
try to call getchar() right before main() returns.
(/SUBSYSTEM:CONSOLE) did not worked for my vs2013 (I already had it).
"run without debugging" is not an options, since I do not want to switch between debugging and seeing output.
I ended with
int main() {
...
#if _DEBUG
LOG_INFO("end, press key to close");
getchar();
#endif // _DEBUG
return 0;
}
Solution used in qtcreator pre 2.6. Now while qt is growing, vs is going other way. As I remember, in vs2008 we did not need such tricks.
just put as your last line of code:
system("pause");
Here's a solution that (1) doesn't require any code changes or breakpoints, and (2) pauses after program termination so that you can see everything that was printed. It will pause after either F5 or Ctrl+F5. The major downside is that on VS2013 Express (as tested), it doesn't load symbols, so debugging is very restricted.
Create a batch file. I called mine runthenpause.bat, with the following contents:
%1 %2 %3 %4 %5 %6 %7 %8 %9
pause
The first line will run whatever command you provide and up to eight arguments. The second line will... pause.
Open the project properties | Configuration properties | Debugging.
Change "Command Arguments" to $(TargetPath) (or whatever is in "Command").
Change "Command" to the full path to runthenpause.bat.
Hit OK.
Now, when you run, runthenpause.bat will launch your application, and after your application has terminated, will pause for you to see the console output.
I will post an update if I figure out how to get the symbols loaded. I tried /Z7 per this but without success.
add “| pause” in command arguments box under debugging section at project properties.
You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:
int a = 0;
scanf("%d",&a);
return YOUR_MAIN_CODE;
and this way the window would not close until you enter data for the a variable.
Just press CNTRL + F5 to open it in an external command line window (Visual Studio does not have control over it).
If this doesn't work then add the following to the end of your code:
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
This wait for you to press a key to close the terminal window once the code has reached the end.
If you want to do this in multiple places, put the above code in a method (e.g. private void Pause()) and call Pause() whenever a program reaches a possible end.
A somewhat better solution:
atexit([] { system("PAUSE"); });
at the beginning of your program.
Pros:
can use std::exit()
can have multiple returns from main
you can run your program under the debugger
IDE independent (+ OS independent if you use the cin.sync(); cin.ignore(); trick instead of system("pause");)
Cons:
have to modify code
won't pause on std::terminate()
will still happen in your program outside of the IDE/debugger session; you can prevent this under Windows using:
extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
if (IsDebuggerPresent())
atexit([] {system("PAUSE"); });
...
}
Either use:
cin.get();
or
system("pause");
Make sure to make either of them at the end of main() function and before the return statement.
You can also use this option
#include <conio.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
.
.
.
getch();
return 0;
}
In my case, i experienced this when i created an Empty C++ project on VS 2017 community edition. You will need to set the Subsystem to "Console (/SUBSYSTEM:CONSOLE)" under Configuration Properties.
Go to "View" then select "Property Manager"
Right click on the project/solution and select "Property". This opens a Test property page
Navigate to the linker then select "System"
Click on "SubSystem" and a drop down appears
Choose "Console (/SUBSYSTEM:CONSOLE)"
Apply and save
The next time you run your code with "CTRL +F5", you should see the output.
Sometimes a simple hack that doesnt alter your setup or code can be:
Set a breakpoint with F9, then execute Debug with F5.
Since running it from VS attaches the VS debugger, you can check for an attached debugger:
if (Debugger.IsAttached)
{
Console.WriteLine("Debugger is attached. Press any key to exit.");
Console.ReadKey();
}
I guess the only caveat is that it'll still pause if you attach any other debugger, but that may even be a wanted behavior.
Use Console.ReadLine() at the end of the program. This will keep the window open until you press the Enter key. See https://learn.microsoft.com/en-us/dotnet/api/system.console.readline for details.
Visual Studio 2015, with imports. Because I hate
when code examples don't give the needed imports.
#include <iostream>;
int main()
{
getchar();
return 0;
}
Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:
The debug window retains the contents of the WSL shell window that closed.
The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.
It should be added that things have changed since then. On Windows 11 (probably 10, I can't check any more) the new Terminal app that now houses the various console, PowerShell and other sessions has its own settings regarding closing. Look for it in Settings > Defaults > Advanced > Profile termination behavior.
If it's set to close when a program exits with zero, then it will close, even if VS is told otherwise.
Go to Setting>Debug>Un-check close on end.

How do I stop a command prompt from appearing in a Win32 C application?

I really have no idea why this is happening...
I created a win32 application in emacs, and whenever I make it and run it (not through the command prompt), a command prompt window pops up under the window. If I build a win32 application in Code::Blocks, and just run its default template, then it runs without a command prompt window. I looked all through the code of both and can't figure out what might cause this...
I thought it was because I included some printf() statements in there, but I didn't want them to stay there (they were for debugging), so I wrote a macro:
#define DEBUG
in main.c, and
#ifdef DEBUG
#include<stdio.h>
#define DBG printf
#else
#define DBG
#endif
in a header (included after the #define DEBUG of course).
When I undef'd DEBUG, the window still showed up... I don't know what I am doing to make it happen, what sorts of things cause a command prompt window to show up in a win32 application? I tried using all the ****Ex() windows functions instead of just CreateWindow(), etc, but that didn't change anything. I checked and re-checked the class definition and registration, to no avail, and made sure I didn't forget a printf() statement (which would have caused an error even if I did, since stdio.h isn't included unless DEBUG is defined).
This is what I included:
#include<windows.h>
#include<windowsx.h>
#include"main.h"
#include"windowproc.h"
anyone know what can cause this? I even commented out all of my stdio, DBG, printf junk, and it still showed up, and I swear there's no difference between my code and the Code::Blocks generated code, aside from my use of HANDLE_MSG and a few extra functions to split up the code.
Update
I am using MinGW 3.4.5.
using the -mwindows switch worked, thanks
Try linking with the -mwindows switch.
Your program should also have the main method read like so:
int WINAPI WinMain(
....
)
as opposed to the traditional int main().
Related threads:
Why does my QT4.5 app open a console window under Windows?
GCC / C how to hide console window?
Windows makes a difference between "console" and "Windows" applications. Console applications will always be run with an associated terminal.
See this question for details on the differences.
Don't know what compiler you are using but I know GCC needs the -mwindows option to suppress the command line window.

Resources