3

我正在尝试编写一个非常简单的程序来替换现有的可执行文件。它应该稍微调整它的参数并使用新参数执行原始程序。它应该由第三方库自动且静默地调用。

它运行良好,但它会弹出一个控制台窗口来显示调用程序的输出。我需要那个控制台窗口不存在。我不关心程序的输出。

我最初的尝试是设置为控制台应用程序,所以我想我可以通过编写一个新的 Windows GUI 应用程序来解决这个问题。但它仍然会弹出控制台。我假设原始命令被标记为控制台应用程序,因此 Windows 会自动为其提供一个控制台窗口以在其中运行。我还尝试用对 system() 的调用替换我对 _exec() 的原始调用,以防万一。没有帮助。

有谁知道我怎样才能让这个控制台窗口消失?

这是我的代码:

int APIENTRY _tWinMain(HINSTANCE hInstance,
                       HINSTANCE hPrevInstance,
                       char*    lpCmdLine,
                       int       nCmdShow)
{
    char *argString, *executable;
    // argString and executable are retrieved here

    std::vector< std::string > newArgs;
    // newArgs gets set up with the intended arguments here

    char const ** newArgsP = new char const*[newArgs.size() + 1];
    for (unsigned int i = 0; i < newArgs.size(); ++i)
    {
        newArgsP[i] = newArgs[i].c_str();
    }
    newArgsP[newArgs.size()] = NULL;

    int rv = _execv(executable, newArgsP);
    if (rv)
    {
        return -1;
    }
}
4

3 回答 3

4

使用CreateProcess函数而不是 execve。对于 dwCreationFlags 参数,传递 CREATE_NO_WINDOW 标志。您还需要将命令行作为字符串传递。

例如

STARTUPINFO startInfo = {0};
PROCESS_INFORMATION procInfo;
TCHAR cmdline[] = _T("\"path\\to\\app.exe\" \"arg1\" \"arg2\"");
startInfo.cb = sizeof(startInfo);
if(CreateProcess(_T("path\\to\\app.exe"), cmdline, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &startInfo, &procInfo))
{
   CloseHandle(procInfo.hProcess);
   CloseHandle(procInfo.hThread);
}
于 2009-12-31T19:55:27.837 回答
1

啊哈,我想我在MSDN上找到了答案,至少如果我准备使用 .NET 的话。(我不认为我真的应该这样做,但我暂时忽略它。)

 System::String^ command = gcnew System::String(executable);
 System::Diagnostics::Process^ myProcess = gcnew Process;
 myProcess->StartInfor->FileName = command;
 myProcess->StartInfo->UseShellExecute = false; //1
 myProcess->StartInfo->CreateNowindow = true;   //2
 myProcess->Start();

重要的是标记为 //1 和 //2 的那两行。两者都需要在场。

我真的不明白这里发生了什么,但它似乎工作。

于 2009-12-21T13:49:44.047 回答
0

您需要创建一个非控制台应用程序(即 Windows GUI 应用程序)。如果这个应用程序所做的只是处理文件或其他什么,那么您将不需要 WinMain、注册任何窗口或有消息循环 - 只需像控制台应用程序一样编写代码。当然,您将无法使用 printf 等。当你开始执行它时,使用 exec() 系列函数,而不是 system()。

于 2009-12-21T11:15:43.973 回答