Document.ProtectDocument 方法 (2007 system)

更新: 2008 年 7 月

由 Visual Studio Tools for Office 运行时调用,以便可以在保存了缓存数据后对文档重新应用密码保护。

命名空间:  Microsoft.Office.Tools.Word
程序集:  Microsoft.Office.Tools.Word.v9.0(在 Microsoft.Office.Tools.Word.v9.0.dll 中)

语法

声明
Protected Overridable Sub ProtectDocument
用法

Me.ProtectDocument()
protected virtual void ProtectDocument()

备注

如果文档受密码保护,且包含可能在运行时发生更改的缓存数据,则应在 Word 的文档级项目中重写此方法。在此方法的实现中,应使用 Protect 方法对文档提供保护。

对于受密码保护的文档,在默认情况下,保存文档时将不保持对其缓存数据所做的更改。若要保存对缓存数据所做的更改,必须重写项目中的下列方法:

  • UnprotectDocument. 保存文档时,Visual Studio Tools for Office 运行时将调用此方法。请向此方法中添加可暂时取消对文档的保护的代码。这样就可以保存对缓存数据所做的更改。

  • ProtectDocument. 保存文档后,Visual Studio Tools for Office 运行时将调用此方法。请向此方法中添加对文档重新应用保护的代码。

有关更多信息,请参见如何:在受密码保护的文档中缓存数据

Visual Studio Tools for Office 运行时会始终调用 ProtectDocument 方法,即使在因为某些与密码保护无关的错误而无法保存缓存的数据时,情况也不例外。例如,在通过实现 ICachedType 接口来自定义在文档中存储缓存数据的方式时,即使 ICachedType 实现引发了阻止保存缓存数据的异常,也会调用 ProtectDocument 方法。

示例

下面的代码示例演示如何重写 ProtectDocument 方法,以重新应用因重写 UnprotectDocument 方法而移除的保护。若要使用此代码,请从 Word 文档级项目内的 ThisDocument 类中运行它。该代码假定密码存储在一个名为 securelyStoredPassword 的字段中。

<CachedAttribute()> _
Public CachedString As String = "This string is cached in the document."

Private protectionTypeValue As Word.WdProtectionType

Protected Overrides Sub UnprotectDocument()
    If Me.ProtectionType <> Word.WdProtectionType.wdNoProtection Then
        protectionTypeValue = Me.ProtectionType
        Me.Unprotect(securelyStoredPassword)
    End If
End Sub

Protected Overrides Sub ProtectDocument()
    Me.Protect(protectionTypeValue, Password:=securelyStoredPassword)
End Sub
[CachedAttribute]
public string CachedString = "This string is cached in the document.";

private Word.WdProtectionType protectionTypeValue;

protected override void UnprotectDocument()
{
    if (this.ProtectionType != Word.WdProtectionType.wdNoProtection)
    {
        protectionTypeValue = this.ProtectionType;
        this.Unprotect(ref securelyStoredPassword);
    }
}

protected override void ProtectDocument()
{
    this.Protect(protectionTypeValue, ref missing,
        ref securelyStoredPassword, ref missing, ref missing);
}

权限

另请参见

参考

Document 类

Document 成员

Microsoft.Office.Tools.Word 命名空间

UnprotectDocument

其他资源

缓存数据

如何:在受密码保护的文档中缓存数据

修订记录

日期

修订记录

原因

2008 年 7 月

新增主题。

SP1 功能更改。