2011. február 28., hétfő

Work with MS Word DisplayAlerts


I have the following code:

MsWord.DisplayAlerts := wdAlertsNone;
MsWord.ScreenUpdating := False;
WordDoc := MsWord.Documents.Add(Template, False);

When the file referenced by "Template" is already in use by another document, I will still get a "File in use" dialog (which is bad enough as it is only a template. It shouldn't be opened for editing anyway. But Documents.Add does this by default: there is no readonly option). Isn't DisplayAlerts supposed to supress this dialog?


You can check the file yourself before passing it off to Word (not tested with Office 11):

{ ... }
  ComObj, ActiveX, Word2000;

  TStorageResult = (srNotOpen, srOpen, srNotStorageFile, srFileNotFound,
    srNotOpenButNotWordDocument, srNotOpenButUnsureWordDocument);

function CheckWordDocument(const AWordDocument: WideString): TStorageResult;
  vResult: HRESULT;
  vStatStg: TSTATSTG;
  oStorage: IStorage;
  Result := srOpen;
  if FileExists(AWordDocument) then
    if StgIsStorageFile(PWideChar(AWordDocument)) = S_OK then
      {Must check for S_OK...cannot use Succeeded().}
      vResult := StgOpenStorage(PWideChar(AWordDocument), nil, STGM_SHARE_EXCLUSIVE
        or STGM_READWRITE, nil, 0, oStorage);
      if Succeeded(vResult) then
        Result := srNotOpen;
        if oStorage.Stat(vStatStg, 0) = S_OK then
          if not IsEqualCLSID(CLASS_WordDocument, vStatStg.clsid) then
            Result := srNotOpenButNotWordDocument;
          Result := srNotOpenButUnsureWordDocument;
        oStorage := nil;
      Result := srNotStorageFile;
    Result := srFileNotFound;

procedure TForm1.Button1Click(Sender: TObject);
  vStorageResult: TStorageResult;
  vStorageResult := CheckWordDocument('C:\Your.doc');
  case vStorageResult of
      ShowMessage('The document is not open.');
      ShowMessage('The document is open.');
      ShowMessage('The document is not a storage document.');
      ShowMessage('The document was not found.');
      ShowMessage('The document is not open, but it is not a Word document.');
      ShowMessage('The document is not open, but it does not look like a Word document.');

Nincsenek megjegyzések:

Megjegyzés küldése