Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Win32 console problem

is it possible to create a program that works as console application if started from the console and works as windows program (with GUI) when started otherwise?

If it is possible - how can I do that?

regards Tobias

like image 897
Tobias Langner Avatar asked Jan 18 '11 14:01

Tobias Langner


2 Answers

If you set the program up to build as a GUI program you can then attempt to attach to the console using AttachConsole(). You you attach OK then you were started from a console and you can proceed to redirect your standard handles to the newly attached console.

In this way you can start up and see if you are being started from a console that you can attach to and if so become a console program. If you cant attach you can show a GUI.

I've had some success with this, the main problem I have is redisplaying the command window's prompt when my program exits (which is how normal console programs operate), but I expect you could do something clever (read the console buffer on start up and find the prompt to redisplay when you exit?) if you really wanted to ...

like image 121
Len Holgate Avatar answered Oct 04 '22 13:10

Len Holgate


If you need the program to act as a console application (e.g. print the usage information to the console) you must complile as a console application. A windows application will not have access to the console and cmd.exe will not wait for it to finish before printing the prompt and accepting the next command.

The best solution is to have two versions, one for command line and one for the GUI (which users usually run via a link on the desktop or start menu).

If you insist on using a single binary you will have to live with a console window appearing, at least for a short time. You can get rid of the console window using

FreeConsole();

You can tell that your application was run from GUI if it is the only process attached to the console. You can use GetConsoleProcessList to find the list of processes attached to the console.

like image 37
John Avatar answered Oct 04 '22 15:10

John