How can I run a windows batch file but hide the command window?

前端 未结 10 1874
情深已故
情深已故 2020-11-30 01:40

How can I run a windows batch file but hiding the command window? I dont want cmd.exe to be visible on screen when the file is being executed. Is this possible?

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 02:33

    Native C++ codified version of Oleg's answer -- this is copy/pasted from a project I work on under the Boost Software License.

    BOOL noError;
    STARTUPINFO startupInfo;
    PROCESS_INFORMATION processInformation;
    ZeroMemory(&startupInfo, sizeof(startupInfo));
    startupInfo.cb = sizeof(startupInfo);
    startupInfo.dwFlags = STARTF_USESHOWWINDOW;
    startupInfo.wShowWindow = SW_HIDE;
    noError = CreateProcess(
        NULL,                                           //lpApplicationName
        //Okay the const_cast is bad -- this code was written a while ago.
        //should probably be &commandLine[0] instead. Oh, and commandLine is
        //a std::wstring
        const_cast(commandLine.c_str()),        //lpCommandLine
        NULL,                                           //lpProcessAttributes
        NULL,                                           //lpThreadAttributes
        FALSE,                                          //bInheritHandles
        CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,  //dwCreationFlags
        //This is for passing in a custom environment block -- you can probably
        //just use NULL here.
        options.e ? environment : NULL,                 //lpEnvironment
        NULL,                                           //lpCurrentDirectory
        &startupInfo,                                   //lpStartupInfo
        &processInformation                             //lpProcessInformation
    );
    
    if(!noError)
    {
        return GetLastError();
    }
    
    DWORD exitCode = 0;
    
    if (options.w) //Wait
    {
        WaitForSingleObject(processInformation.hProcess, INFINITE);
        if (GetExitCodeProcess(processInformation.hProcess, &exitCode) == 0)
        {
            exitCode = (DWORD)-1;
        }
    }
    
    CloseHandle( processInformation.hProcess );
    CloseHandle( processInformation.hThread );
    

提交回复
热议问题