使用msscript.ocx组件的ScriptControl调用VBS脚本

   
在stdafx.h文件中,导入msscript.ocx
// 64位windows
#import "c:\windows\syswow64\msscript.ocx" /*raw_interfaces_only, raw_native_types,*/ no_namespace, named_guids \
    rename("Error", "ScriptError")
 
在cpp文件中,实现调用脚本。
 /**********************************************************
    Created on 2012/7/16
    ***********************************************************/
    CoInitialize(NULL);
    try
    {

        HANDLE hFile = CreateFile(
            _T("e:\\VBS脚本\\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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值