简体   繁体   English

关闭控制台而不退出

[英]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. 例如,打开自定义创建的控制台,或者如果我想打开HWND且不希望控制台在后台运行。

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). 是的,我知道我可以使用WINAPIWinMain但是我希望我的程序也可以在Linux系统上执行(此处不带HWND )。

C++ has no idea of the console. C ++不了解控制台。 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. 如果您需要操纵控制台,那么您将需要为正在运行的系统使用API​​。

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. 为此,您可以提供一个公共接口,然后使用预处理器有条件地编译您需要基于OS符号进行的API调用。

The common way to accomplish this is to use conditional compilation to implement WinMain on windows, and main on other platforms. 做到这一点的常用方法是使用条件编译来实现WinMain在Windows中,并main在其他平台上。

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: 对于Windows:

I used to use ShowWindow (GetConsoleWindow(), SW_HIDE); 我曾经使用ShowWindow (GetConsoleWindow(), SW_HIDE); in such case, however if you don't need console, you shouldn't create console app project. 在这种情况下,但是,如果您不需要控制台,则不应创建控制台应用程序项目。


For Linux: 对于Linux:

(I'm not a Linux guy, so you need to wait for other answers) (我不是Linux专家,所以您需要等待其他答案)


For MAC: 对于MAC:

Not MAC developer either :) 不是MAC开发人员:)


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: 在Linux上,您可以执行以下操作:

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

to detach from terminal. 与终端分离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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