天天看點

C++程式調用cmd指令行 執行bat等應用(XP,WIN7差别)

調用bat檔案或者exe 或者可執行的cmd指令。可以使用CreateProcess,WinExec。這裡推薦使用CreateProcess。

因為官方文檔說:Note  This function is provided only for compatibility with 16-bit Windows. Applications should use the CreateProcess function.

具體代碼:

頭檔案

#pragma once

class CRunBatXp

{

public:

CRunBatXp(void);

~CRunBatXp(void);

void RunBat();

bool TPFExcute(const char *cmd);

};

源檔案:

#include "StdAfx.h"

#include "RunBatXp.h"

CRunBatXp::CRunBatXp(void)

{

}

CRunBatXp::~CRunBatXp(void)

{

}

void CRunBatXp::RunBat()

{

bool bret=false;

char szFilePath[_MAX_PATH]={0};

::GetModuleFileName(NULL, szFilePath, _MAX_PATH);

char *pStr=strrchr(szFilePath,'\\');

if (pStr)

{

*(pStr+1)=0x00;

}

std::string strpath=szFilePath;

strpath+="ISetup.bat";

//XP系統特别處理

strpath.insert(strpath.begin(),1,'\"');

strpath.append("\"");

//XP系統特别處理 end

UINT uret=0;

TPFExcute(strpath.c_str());

DEBUG_LOG("WinExec傳回值:%d,error:%d",uret,GetLastError());

}

bool CRunBatXp::TPFExcute(const char *cmd)

{

STARTUPINFO s;

GetStartupInfo(&s);

s.cb = sizeof(s);

s.dwFlags =STARTF_USESHOWWINDOW; 

s.wShowWindow =SW_HIDE;

PROCESS_INFORMATION pi;

memset(&pi,0x00,sizeof(PROCESS_INFORMATION));

DWORD dwCreationFlags=0;

char szcmd[1024]={0};

strlcpy(szcmd,cmd,1024);

if(CreateProcess(NULL,szcmd,NULL,NULL,TRUE,dwCreationFlags,NULL,NULL,&s,&pi))

WaitForSingleObject(pi.hProcess ,INFINITE); 

return true;

}

else

{

DEBUG_LOG("執行%s指令失敗",szcmd);

return false;

}

}

注意事項:

win7下的執行指令直接輸入字元創串即可,c:\xx.bat

winxp下字元串需要被雙引号包圍,"c:\xx.bat"

這也是windows的坑吧

繼續閱讀