如何在Windows中从C++程序执行另一个exe文件

20

我希望我的C++程序在Windows中执行另一个.exe文件,我该怎么做?我正在使用Visual C++ 2010。

这是我的代码:

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    unsigned int input;
    cout << "Enter 1 to execute program." << endl;
    cin >> input;
    if(input == 1) /*execute program here*/;
    return 0;
}

您可以使用https://dev59.com/6XRB5IYBdhLWcg3w4bGv来调用任何可执行文件。 - superarce
1
你可以使用ShellExecute来实现这个功能。 - Michael
这个可以运行:system("程序执行名称在此") - turnt
可能是重复的问题:在C++中执行另一个程序 - user1810087
1
you can use Google search! - gdbcore
我使用了谷歌搜索并找到了一个在Unix上有效但在Windows上无效的答案。 :) - ThePrince
5个回答

35

这是我之前寻找答案时发现的解决方案。
它指出,应该始终避免使用system(),因为:

  • 它占用资源较多。
  • 它会破坏安全性——你不知道它是一个有效的命令还是在每个系统上执行相同的操作,甚至可能启动你没有打算启动的程序。危险在于当你直接执行一个程序时,它获得了与你的程序相同的特权,这意味着如果例如你正在作为系统管理员运行,则刚刚无意中执行的恶意程序也将作为系统管理员运行。
  • 杀软讨厌它,你的程序可能会被标记为病毒。

相反,可以使用CreateProcess()。
Createprocess()用于只启动一个.exe并为其创建一个新进程。应用程序将独立于调用应用程序运行。

#include <Windows.h>

void startup(LPCSTR lpApplicationName)
{
    // additional information
    STARTUPINFOA si;
    PROCESS_INFORMATION pi;

    // set the size of the structures
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    // start the program up
    CreateProcessA
    (
        lpApplicationName,   // the path
        argv[1],                // Command line
        NULL,                   // Process handle not inheritable
        NULL,                   // Thread handle not inheritable
        FALSE,                  // Set handle inheritance to FALSE
        CREATE_NEW_CONSOLE,     // Opens file in a separate console
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi           // Pointer to PROCESS_INFORMATION structure
    );
        // Close process and thread handles. 
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
}

3
有时候,'argv'变量可能会超出范围。通常情况下,我会将另一个全局变量赋值为'argv'的值,并使用它代替。 - James Stow

19
你可以使用 system 函数。
int result = system("C:\\Program Files\\Program.exe");

1
我们可以向该程序传递参数吗? - Shayan

12

5
您可以使用system进行电话呼叫。
system("./some_command")

3

我相信这个答案适用于不同的程序,我用Chrome测试过。

// open program.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "string"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string command = "start chrome https://www.google.com/";
    system(command.c_str());

    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接