Win32窗口程序使用控制台

Win32窗口程序使用控制台对应的函数是AllocConsole和FreeConsole。
向控制台输出

AllocConsole() ;
HANDLE hd = GetStdHandle(STD_OUTPUT_HANDLE) ;
WriteConsole(hd , "hello console\n", sizeof("hello console\n") , NULL , NULL );
CloseHandle(hd) ;
FreeConsole();

可以正常打开和关闭Console控制台输出。
如果想使用std::cout标准输出函数,可以使用freopen重定向函数到"conout$"特殊文件。

  AllocConsole();
  freopen("conout$","w",stdout);
  freopen("conout$","w",stderr);
  do {
    
    
    std::cout << "try connect services...";
    pSetting = Class::GetClassFromFile(GetURL(), CLASS_TYPE(CApplicationSetting) );
    if (Null == pSetting) {
    
    
      std::cout << "failed" << std::endl;
      Sleep(5000);
    }
    else {
    
    
      std::cout << "successed" << std::endl;
    }
  }
  while(Null == pSetting);
  FreeConsole();

这个时候可以用标准输出函数输出文本信息,但是FreeConsole并不会关掉控制台窗口,需要再调用freopen重定向函数重定向回默认控制台输出流,就可以关闭控制台窗口了。

  FreeConsole();
  freopen("conout$","w",stdout);
  freopen("conout$","w",stderr);

猜你喜欢

转载自blog.csdn.net/qq_31042143/article/details/107307860