c++ 调用cmd并执行语句的三种方法

 

    本文旨在实现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;
}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值