Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an Application without a Window

Tags:

c++

c

winapi

How would you program a C/C++ application that could run without opening a window or console?

like image 219
kiewic Avatar asked Oct 22 '08 02:10

kiewic


People also ask

How can I open console application without Windows?

If you do not know what I am talking about: press Win+R, type “help” and press ENTER. A black console window will open, execute the HELP command and close again. Often, this is not desired. Instead, the command should execute without any visible window.


1 Answers

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.

like image 50
computinglife Avatar answered Sep 28 '22 09:09

computinglife