How to hide windows console in c++ tcc - c++

How to hide console window,
Compiler is tiny C
//Tiny C -> http://download.savannah.gnu.org/releases/tinycc/
#include <stdlib.h>
int main()
{
system("Taskkill /IM test.exe /F");
return 0;
}

When operating system starts application, it lookups special description table in EXE file called IMAGE_OPTIONAL_HEADER. This structure contains so called Subsystem field. When Subsystem is IMAGE_SUBSYSTEM_WINDOWS_CUI - OS attaches console window to this process. Otherwise, console window will not be added.
Compilers/linkers usually have parameters to set output application subsystem type, e.g. when you link your code using Microsoft Linker you can add /SUBSYSTEM:WINDOWS parameter and you will not see console window when starting your application.
The other way: compiler may automatically decide to set EXE subsystem to Console when seeing main function in your code, or set GUI subsystem when you have WinMain as entry point.
About TCC: I see -Wl,-subsystem=gui option in TCC documentation, but seems it is not worked. So try to send a bugreport or use more mature compiler/linker.

Related

No console application on Linux

On Windows I normally create a Windows Desktop Application, this is because console applications display a brief black box on the screen.
I am using CodeBlocks on Linux Mint, how could I do the equivalent of the above but on Linux?
I do not want to hide the terminal window after it has been displayed.
Linux does not have the same "subsystem" concept as windows: there is no difference or separation between console and desktop applications. When you start an application on Linux, it will not open a console window, unless the programmer explicitly programmed it to open one.
If the application writes anything to stdout or stderr, what happens with that depends on how exactly the application got started. By default, the application inherits the stdout and stderr of its parent process. If the application is being started from a terminal, the output will be visible on the terminal. If the application was started by the desktop environment from a menu entry, the output may go to a log file or it may be lost.
If you see a terminal window open when you run your program from the IDE, that's something that the IDE is doing for you, it's not your application. If it bothers your, I would think that the IDE has a way to disable this behavior in settings.
Look into QT. It is a GUI framework that works on Linux.
You can write your code without creating a main window (or maybe you have to have a main window but it can be always hidden... it's been a while since I've used it).
Be aware though, that you may run into usability issues with this type of design... the user has no way of knowing if your app was launched or if it succeeded, when it's completed, etc.
The simple way is to use (e.g.) xterm [or gnome-terminal] to get a terminal window.
Then, invoke your program from the shell [manually]:
/path_to_my_program
You may be able to configure codeblocks to do this for you.
Or, you could add some code that holds the default window open:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid = fork();
if (pid != 0) {
waitpid(pid,NULL,0);
while (1) sleep(1);
}
long double n;
n=5;
printf("n= %Lf\n",n);
return 0;
}
UPDATE:
The invocation command can be controlled from: Settings -> Environment -> General Settings
The default is to invoke in an xterm sub-window [popup]. You may be able to change the settings to (re)use an existing [terminal] window.
Note that [a codeblocks program] cb_console_runner is used. You may be able to replace this with something more to your liking.
I do not want a GUI nor a terminal popup...
You'll need some sort of terminal to run the command in. This could be a script that diverts stdin/stdout/stderr as appropriate [and suppresses the invocation of a sub-window], so you'll have to experiment a bit.
As I mentioned above, you can just open a terminal window outside of codeblocks and then run the command manually inside it. Technically, this is not a popup. But, you lose the [automatic] debugger invocation.

Is my application runs from inside Visual Studio vs. by executing an EXE file

As I often test my binaries inside/outside Microsoft Visual Studio 2017, I want to control the behavior of my code in C/C++ console projects.
One for code for when I run .exe from within Visual Studio in Release mode.
Another when I just click my .exe from Explorer.
What flag or function should I use to know if my .exe was started from inside Visual Studio or not.
What I would like to achive is the:
#if !_RELEASE
system("pause"); // prevents auto shutdown of my .exe in Explorer
// double click
#endif
where _RELEASE is some kind of trait that triggers code in Studio launches,
but not visible in Explorer double click.
What flag or function should I use to know if my process was startded from inside Visual Studio or not.
You shouldn't do such behavior control from inside your program code. That's bad design, and clutters your program code with decisions that should be left on the caller.
I'd recommend if you need different behaviors of your program (e.g. running in background or with visible GUI), this should be controlled with e.g. configuration files or command line parameters.
You can do that for both, Visual Studio settings to specify cmd line parameters, or using a different configuration file, or even a combination of both.
As you seem to insist for a solution of your idea how to fiddle with this in the best way:
You can use the WINAPI functions to iterate through your parent process IDs and check if one of these is matching the "Visual Studio" module.
Here's a Q&A which links to the technique:
How can I reliably check whether one Windows process is the parent of another in C++?
It not exactly solution, but:
Raymond Chen(Microsoft winapi guru*) is most close in spirit to the problem I facing, helping me detect in what mode or circumstances I run my console session.
How can I tell whether my console program was launched from Explorer or from a command prompt?
printf("this process = %d\n", GetCurrentProcessId());
DWORD count = GetConsoleProcessList(nullptr, 0);
if (count == 1) {
printf("I'm the last one!\n");
Sleep(2000);
}
else {
printf("I'm not the last one! %d\n", count);
}

Run a console application and then close the console and run in background in C++

I want to make a console application in C++ and then when the information is displayed, close the console and run in background. Is this possible? Is another way to do that? Python maybe?
You will have to either close the console window while the process is still running, which is system dependent, or start another process, and even though the standard library offers the system function to do that, its argument is a system dependent command line.
So the upshot is: this is system dependent.
In Windows the full-version of Microsoft's Visual Studio IDE has always, as far back as I can remember, used a peculiar approach for this, with two executable files devenv.com and devenv.exe. The former is a console subsystem executable, which by default runs the latter, which is a GUI subsystem executable:
[C:\]
> where devenv
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.com
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe
[C:\]
> _
The basic idea here is that for historical reasons the command interpreter's search for an executable finds the .com file first, so the command devenv just works, either for starting the IDE or just getting the help text via the /? option.
Yes, this is possible with a small variant:
fork another process. But this is heavily system dependent:
posix/linux allow to simply clone the process;
windows requires new process to be created from an executable. You then have to communicate the state. Its less trivial as explained in this article, in the paragraph on porting fork())
then exit the program (it's the only way to give back control to the console).
On Windows use ShowWindow(FindWindowA("ConsoleWindowClass", NULL), false) to hide the console window. It will still be running in the background and is not visible on the taskbar.
However you will have to run a task manager like Taskmgr.exe to find it and shut it down.
#include <windows.h>
#include <iostream>
using namespace std;
int main () {
cout<<"Some information is displayed.. \n\n";
Sleep(5000);
cout<<"wait.. the console is going to hide and run in background.. \n";
Sleep(5000);
ShowWindow(FindWindowA("ConsoleWindowClass", NULL), false);
while(true) {
// Do your hidden stuff in here
}
return 0;
}
The other answers given here overcomplicate things. The most easy way to close the console window in Windows is to simply detach from it. Once the last user of a console window datached, the console window gets closed.
If you start a program from a CLI (e.g. cmd.exe) then this CLI is also attaches to to the console and thus the console window will not close.
Anyway, detaching from a console is as simple as calling
FreeConsole();
… done!
Also you can attach to a newly created console at any time using AttachConsole, which takes a process ID. Now in a CLI situation the parent will usually be the CLI shell, so you may want to attach to the console of that.

Granting c++ program administrative rights through UAC at startup

So I've done some research, but I'm interested in understanding how one would make his program ask for administrative privileges from the UAC before its execution. Would this require one to use "runas" inside the ShellExecute()? I realize that this is something I will need to understand into my adventure of programming, as just about every program I have installed has asked me this. So for example, if I gave a program privileges at start up it would be able to execute any batch file or cmd statement through the system() function correct?
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
system("notepad");
return 0;
}
You can set the requireAdmin in the executables manifest file, and then this will request your application to be raised to admin, the user may have to supply additional credentials (like run as).
It will put a little shield against your application icon in explorer.
In Visual Studio
select properties on your project,
then open up "Configuration Properties"
then open up Linker
Select "Manifest File"
and modify "UAC Execution Level" to requireAdministrator
you can do this other ways but that's one of the easiest.
So, in your example if the program you wrote had UAC execution level set to "requireAdministrator" then the program you call would then also be elevated in this case notepad. (I think that there may be some way to make sure that you are not elevated, but I have never done that)

Starting a hidden C++ program

I am creating a C++ program with Visual Studio 2010 that is supposed to run on the background of my machine.
Therefore when I start it, I shouldn't see the CMD screen while it is running. How can I do this? Do I have to use the Win32 API or a normal C++ program will suffice?
Please note that my program has no GUI at all.
Use WinMain() :
#include <windows.h>
int WINAPI WinMain(HINSTANCE inst,HINSTANCE prev,LPSTR cmd,int show)
{
// program starts here
return 0;
}
// int main() <-- remove main()
Then ake sure your project settings are set so that you build a "Win32" program and not a "Console" program.
Edit: As #Sehe points out, winMain may not be necessary, although I am not quite sure where this option lies.
Run it as a service See here.
Very often a program running under Windows without a "face" (eg, with no user interface at all) is implemented as a Service.
In windows, Daemon programs are implemented as Services.
Simply make it a GUI application instead of a command line application. Right click the project -> Properties -> Configuration Properties -> Linker -> System -> SubSystem -> Windows (/SUBSYSTEM:WINDOWS).
You can run as a Windows process (which doesn't attach to a console), but never create a window. the main difference is the signature of WinMain, and the flags to the compiler.
Go to File -> New Project, select the standard Windows Application, then delete everything except WinMain.