Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

c++ - Is there any way of stopping _popen opening a dos window?

I am using _popen to start a process to run a command and gather the output

This is my c++ code:

bool exec(string &cmd, string &result)
{
   result = "";

   FILE* pipe = _popen(cmd.c_str(), "rt");
   if (!pipe)
      return(false);

   char buffer[128];
   while(!feof(pipe))
   {
        if(fgets(buffer, 128, pipe) != NULL)
               result += buffer;
   }
   _pclose(pipe);
   return(true);
}

Is there any way of doing this without a console window opening (as it currently does at the _popen statement)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On Windows, CreateProcess with a STARTUPINFO structure that has dwFlags to include STARTF_USESSHOWWINDOW. Then setting STARTUPINFO.dwFlags to SW_HIDE will cause the console window to be hidden when triggered. Example code (which may be poorly formatted, and contains a mix of C++ and WinAPI):

#include <windows.h>
#include <iostream>
#include <string>

using std::cout;
using std::endl;

void printError(DWORD);

int main()
{
  STARTUPINFOA si = {0};
  PROCESS_INFORMATION pi = { 0 };

  si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
  si.wShowWindow = SW_HIDE;
  BOOL result = ::CreateProcessA("c:/windows/system32/notepad.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
  if(result == 0) {
      DWORD error = ::GetLastError();
      printError(error);
      std::string dummy;
      std::getline(std::cin, dummy);
      return error;
  }

  LPDWORD retval = new DWORD[1];
  ::GetExitCodeProcess(pi.hProcess, retval);
  cout << "Retval: " << retval[0] << endl;
  delete[] retval;

  cout << "Press enter to continue..." << endl;
  std::string dummy;
  std::getline(std::cin, dummy);

  return 0;
}

void printError(DWORD error) {
    LPTSTR lpMsgBuf = nullptr;
     FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        error,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );
     cout << reinterpret_cast<char*>(lpMsgBuf) << endl;
     LocalFree(lpMsgBuf);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...