c++ - Boost::process 在 Windows 上隐藏控制台

标签 c++ windows boost

最近发布了 boost 1.64,包括 boost::process。这为启动进程提供了一个简单的界面。之前我使用了独立版本的 boost::process 库(参见 here )。这很好用。我想换到新版本,这样我就可以放弃独立的依赖。

API 有点不同,但一切正常,除了 on thing。在旧版本中,我能够传递特定于 Windows 的上下文对象,这允许我隐藏进程打开的任何控制台窗口。

boost::process::win32_context ctx;
ctx.environment = boost::process::self::get_environment();

STARTUPINFOA stup;
ZeroMemory(&stup, sizeof(stup));
stup.cb = sizeof(stup);
stup.dwFlags = STARTF_USESHOWWINDOW;
stup.wShowWindow = SW_HIDE;
ctx.startupinfo = &stup;

std::vector<std::string> args;
boost::process:child process = boost::process::win32_launch("myprogram", args, ctx);

使用新版本它看起来像这样:

boost::process::environment env = boost::this_process::environment();
boost::process:child process(boost::filesystem::path("myprogram"), env);

除了隐藏控制台窗口外,一切正常。有可能实现吗?

最佳答案

child 构造函数接受一个类型列表,稍后将使用花哨的 ::boost::fusion 方法将其转换为执行实际初始化的调用链。所以你可以按任何顺序推送支持类型的参数:

#include <boost/process.hpp>
#include <boost/process/windows.hpp> // for windows::hide that can only be used on Windows

...

::boost::process::environment env = ::boost::this_process::environment();
::boost::process::child ch1("cmd", env, ::boost::process::windows::hide); // ok
::boost::process::child ch2(::boost::filesystem::path("C:\\Windows\\System32\\cmd.exe"), ::boost::process::windows::hide, env); // fine too

有条件地隐藏窗口并不是那么简单,因为 windows::hidewindows::show 是不同的类型,不能在相同的函数参数中传递。在这种情况下,需要编写自定义设置处理程序:

struct show_window
:   ::boost::process::detail::handler_base
{
    private: ::boost::detail::winapi::WORD_ const m_flag;

    public: explicit
    show_window(bool const show) noexcept
    :   m_flag{show ? ::boost::detail::winapi::SW_SHOWNORMAL_ : ::boost::detail::winapi::SW_HIDE_}
    {}

    // this function will be invoked at child process constructor before spawning process
    template <class WindowsExecutor>
    void on_setup(WindowsExecutor &e) const
    {
        // we have a chance to adjust startup info
        e.startup_info.dwFlags |= ::boost::detail::winapi::STARTF_USESHOWWINDOW_;
        e.startup_info.wShowWindow |= m_flag;
    }
};

auto const need_to_show{false};
auto env{::boost::this_process::environment()};
::boost::process::child ch("cmd", env, show_window{need_to_show});

关于c++ - Boost::process 在 Windows 上隐藏控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43582022/

相关文章:

c++ - boost::process 异步 IO 示例不起作用?

c++ - 正确使用 std::result_of_t

windows - 无法在 cygwin 中终止 Windows 进程

windows - PowerShell - Invoke-Sqlcmd 结果到 Export-Csv 设置批处理行限制

windows - 没有图标的QMessageBox

c++ - boost 和 c++11 线程兼容性

c++ - 无法使用 boost 信号量构建应用程序

c++ - 使用指针获取字符在字符串中的位置

c++ - 导出数据成员是否正确? (C++)

c++ - 屏幕坐标到世界坐标