繁体   English   中英

如何从 Windows 中的 C++ 程序执行另一个 exe

[英]How to execute another exe from a C++ program in Windows

我希望我的 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;
}

这是我之前在寻找答案时找到的解决方案。
它指出您应该始终避免使用 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);
}

您可以使用system功能

int result = system("C:\\Program Files\\Program.exe");

使用 CreateProcess() 函数。

有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx

您可以使用system拨打电话

system("./some_command")

我相信这个答案应该适用于不同的程序,我用 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM