简体   繁体   中英

Close console without exit

Is it possible to close the console without shutting down the program?

For example to open a custom created console or if I want to open a HWND and don't want the console in the background.

Yes I know I could use the WINAPI and WinMain but I want my program to be also executable on Linux-Systems (not with an HWND here).

C++ has no idea of the console. If you need to manipulate the console then you are going to need to use the API for the system you are running on to do that.

To do that on your own you could provide a common interface and then using the preprocessor to conditionally compile the API calls you need to make based on the OS symbols.

The common way to accomplish this is to use conditional compilation to implement WinMain on windows, and main on other platforms.

one possible formulation:

#ifdef _WIN32
int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPTSTR lpCmdLine, int)
{
    int argc;
    char ** argv;
    std::tie (argc, argv) = parse_command_line_arguments (lpCmdLine);
#else
int main (int argc, char ** argv)
{
#endif

   return 0

}

For Windows:

I used to use ShowWindow (GetConsoleWindow(), SW_HIDE); in such case, however if you don't need console, you shouldn't create console app project.


For Linux:

(I'm not a Linux guy, so you need to wait for other answers)


For MAC:

Not MAC developer either :)


And as a final piece you will need preprocessor to compile different code for different platforms.

#ifdef _WIN32
//do what is required for windows
#endif
#ifdef __linux__
//do what is required for linux
#endif
#ifdef __APPLE__
//do what is required for OS x machines
#endif 

There is no cross-platform way to do this. On Linux you can do:

int fd = open("/dev/tty", O_RDWR);
ioctl(fd, TIOCNOTTY, NULL);

to detach from terminal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM