本文旨在实现c++程序中调用cmd并完成语句执行
需引入的头文件:#include <windows.h>
需要执行的命令:instsrv GameManagerServer C:\\Windows\\System32\\srvany.exe
语句执行前提:(1) C:\\Windows\\System32\\srvany.exe 存在,
(2)C:\\Windows\\System32\\srvany.exe 已加入系统环境变量(这里不知道的话请百度一下)
语句含义:将srvany.exe加入系统服务,此服务的名字叫做GameManagerServer 。
方法1:system("instsrv GameManagerServer C:\\Windows\\System32\\srvany.exe");
方法2:WinExec("instsrv GameManagerServer C:\\Windows\\System32\\srvany.exe",SW_NORMAL);
方法3:
SHELLEXECUTEINFO ShExecInfo = { 0 };
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = _T("cmd.exe");
ShExecInfo.lpParameters = _T("/k instsrv GameManagerServer C:\\Windows\\System32\\srvany.exe ");
ShExecInfo.lpDirectory = _T("");
ShExecInfo.nShow = SW_HIDE;
ShExecInfo.hInstApp = NULL;
ShellExecuteEx(&ShExecInfo);
cmd /c dir 是执行完dir命令后关闭命令窗口。
cmd /k dir 是执行完dir命令后不关闭命令窗口。
文件Test.cpp如下:
// Test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <shellapi.h>
int _tmain(int argc, _TCHAR* argv[])
{
//执行批处理命令
//方法一
WinExec("instsrv GameManagerServer C:\\Windows\\System32\\srvany.exe",SW_NORMAL);
//方法二
//system("instsrv GameManagerServer C:\\Windows\\System32\\srvany.exe");
//方法三
/*
SHELLEXECUTEINFO ShExecInfo = { 0 };
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = _T("cmd.exe");
ShExecInfo.lpParameters = _T("/k instsrv GameManagerServer C:\\Windows\\System32\\srvany.exe ");
ShExecInfo.lpDirectory = _T("");
ShExecInfo.nShow = SW_HIDE;
ShExecInfo.hInstApp = NULL;
ShellExecuteEx(&ShExecInfo);*/
return 0;
}