如何在 C++ 程序 运行 时间隐藏控制台?

How I can hide the console during c++ program run-time?

如何在 C++ 程序 运行 期间隐藏控制台?

我的编译器:MinGw (g++)

我尝试了很多方法,但都没有用:

  1. 添加-mwindows命令
  2. ShowWindow(GetConsoleWindow(), SW_HIDE);
  3. WinMain(...)

有问题的代码在这里(来自评论):

#include <iostream> 
#include <Windows.h> 

int main() { 
  std::cout << "Recompiling compile app..."; 
  system("taskkill /IM Compile.exe"); 
  system("g++ Compile.cpp -o Compile.exe"); 
  system("Start Compile.exe"); return 0; 
}

如何解决我的问题?

这对我有用 (FreeConsole MSDN)

#include <Windows.h>
// Other includes

int main(void)
{
    FreeConsole();

    // Do whatever you want here
    for (int i = 0; i < 10000; i++)
        std::cout << "You cant see me!" << std::endl;

    return 0;
}

您的问题似乎是由调用 system 函数引起的,该函数默认使用控制台 window 运行。如果您自己的程序需要至少一个控制台 window,此示例将对您有所帮助。如果您不需要任何输出,只需取消注释示例中的行即可。

#include <iostream> 
#include <Windows.h> 

int main() { 
  // Uncomment next line if you don't need output at all
  // FreeConsole();

  std::cout << "Recompiling compile app..."; 
  WinExec("taskkill /IM Compile.exe", SW_HIDE); 
  WinExec("g++ Compile.cpp -o Compile.exe", SW_HIDE); 
  WinExec("C:\Path\To\Compile.exe", SW_HIDE); 

  return 0; 
}

您可以将它与我的旧答案结合起来以达到预期的效果。


旧答案(仍然可能对某些人有帮助);

这个问题已经 answered here and here 了,假设您正在谈论为 Windows 编译 C++ 应用程序。

基本上第一个答案将帮助您编译没有 window 的 windowed 应用程序,第二个是控制台应用程序,它将立即隐藏控制台 window,尽管它将在屏幕上闪烁一秒钟左右。