// testvb.cpp : Defines the entry point for the console application.
//
#import "msscript.ocx" no_namespace
#include "stdafx.h"
#include "tchar.h"
#include "stdio.h"
#include "iostream"
using namespace std;
int main(int argc, char* argv[])
{
CoInitialize(NULL);
try
{
HANDLE hFile = CreateFile(
_T("c:\\checklen.vbs"),
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
DWORD dwFilesize = 0;
DWORD dwActSize =0;
dwFilesize = GetFileSize(hFile, NULL);
BYTE *pBytes = new BYTE[dwFilesize+1];
memset(pBytes, 0, dwFilesize+1);
ReadFile(hFile, pBytes, dwFilesize, &dwActSize,NULL);
CloseHandle(hFile);
_bstr_t bstrScriptBody = (LPCTSTR)pBytes;
_variant_t vtResult;
int nTimeout = 30;
IScriptControlPtr ptrScript;
ptrScript.CreateInstance(__uuidof(ScriptControl));
ptrScript->Timeout = 1000 * nTimeout; //超时设置
ptrScript->PutAllowUI( VARIANT_TRUE );
ptrScript->PutLanguage( _bstr_t(_T("VBScript")) );
//HRESULT hr = ptrScript->ExecuteStatement(bstrScriptBody);
// ptrScript->AddCode( _bstr_t("Function GetValue()\r\n MsgBox \"Hello world\" \r\n GetValue = 5 \r\n End Function\r\n"));
ptrScript->AddCode(bstrScriptBody);
vtResult = ptrScript->Eval(_bstr_t("GetValue"));
// ptrScript->Run(_bstr_t("GetValue"), &vtResult);
ptrScript.Release();
delete[] pBytes;
long lRet = vtResult.iVal;
cout << "VBScript:GetValue->returnValue = " << lRet << std::endl;
cin.get();
}
catch(_com_error &e)
{
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
std::cout<<"VBS Script Engine"<<std::endl;
std::cout<<"COM error occurred, source:"<<(LPCTSTR)bstrSource<<std::endl;
std::cout<<"Description:"<<(LPCTSTR)bstrDescription<<std::endl;
cin.get();
}
CoUninitialize();
return 0;
}
vbs脚本为
Function GetValue()
MsgBox "Hello world"
GetValue = 5
End Function