从C ++自动化Microsoft Project

时间:2016-03-10 10:09:26

标签: c++ ms-project

我们正在尝试使用C ++代码序列读取.MPP文件。以下代码引发了“访问冲突”异常,尽管它看起来应该有效。

#include "stdafx.h"    
    int main()

{
    ::CoInitialize(NULL);
    _MSProjectPtr pApp;
    auto hr = pApp.CreateInstance(__uuidof(Application));
    variant_t toOpen = _T("d:\\work\\Test.mpp");
    variant_t readOnly = true;
    variant_t merge = false;
    auto status = pApp->FileOpen(toOpen, readOnly, merge, vtMissing, vtMissing, vtMissing, vtMissing, vtMissing, vtMissing, vtMissing,
        vtMissing, MSProject::pjDoNotOpenPool);
    auto pProject = pApp->GetActiveProject();
    auto pSummaryTask = pProject->GetProjectSummaryTask();
    auto summaryStart = pSummaryTask->GetStart(); // Access violation raised by this instruction
    auto pTasks = pProject->Tasks; // This call succeeds.
    auto count = pTasks->Count; // Access violation raised by this instruction.
    // Fails at this line with MSP 15.0.4805.1001 (in About box, 15.0.4569.1506 in Control Panel)

    pApp->Quit(MSProject::PjSaveType::pjDoNotSave);
    ::CoUninitialize();
}

stdafx.h文件的内容如下:

#pragma once
#include "targetver.h"
#include <tchar.h>
#import "C:\Program Files (x86)\Microsoft Office\Office16\MSPRJ.OLB" auto_search
using namespace MSProject;

我们缺少初始化步骤吗?

1 个答案:

答案 0 :(得分:0)

我也有这个问题,最后使用 “使用Visual C ++ ClassWizard从Microsoft Office类型库生成“包装类””。

  CMSProject app;
  app.CreateDispatch(L"MSProject.Application");
  auto b = app.FileNew(vtMissing, vtMissing, vtMissing, vtMissing);
  app.SetVisible(TRUE);
  CIProjectDoc p = (LPDISPATCH)app.GetActiveProject();
  CTasks ts = p.get_Tasks();
  auto n = ts.get_Count();
  ts.Add((variant_t)L"abc", vtMissing);