使用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();

你可能感兴趣的:(使用msscript.ocx组件的ScriptControl调用VBS脚本)