⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 documentprotectorform.cs

📁 文件保护 文件保护 文件保护
💻 CS
📖 第 1 页 / 共 3 页
字号:
//***************************************************************************
//
//         Copyright (c) Microsoft Corporation. All rights reserved.
//
//    This code sample is provided "AS IS" without warranty of any kind.
//
//***************************************************************************
#region Using directives

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Diagnostics;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;

#endregion

namespace DocumentProtector
{
    /// <summary>
    /// The main user interface for the application
    /// which allows the user to moidfy a Word document's 
    /// protection state.
    /// </summary>
    partial class DocumentProtectorForm : Form
    {

        #region Form Members
        private Word.ApplicationClass application;
        private TreeNode rootNode;
        private TreeNode bookmarkRootNode;
        private TreeNode formfieldRootNode;
        private TreeNode xmlNodesRootNode;
        private WordProtection.WordProtector wordProtector;
        private string documentPassword;
        #endregion

        #region Constructors
        public DocumentProtectorForm()
        {
            InitializeComponent();

            // Initialize the root area nodes and 
            // the document password.
            this.bookmarkRootNode = new TreeNode(
                Properties.DocumentProtector.bookmarksRootNode_Text);
            this.formfieldRootNode = new TreeNode(
                Properties.DocumentProtector.formFieldsRootNode_Text);
            this.xmlNodesRootNode = new TreeNode(
                Properties.DocumentProtector.xmlNodesRootNode_Text);
            this.documentPassword =
                DataProtection.ProtectData(String.Empty, this.Text);
        }
        #endregion

        #region Helper Methods
        #region Document Actions
        /// <summary>
        /// Saves the currently active document.
        /// </summary>
        private void SaveDocument()
        {
            Debug.Assert(this.wordProtector != null);
            this.wordProtector.Save();
        }

        /// <summary>
        /// Closes the currently open document saving
        /// changes if specified.  If no document is currently
        /// opened, the method does nothing.
        /// </summary>
        /// <param name="saveChanges">
        /// Specifies if changes to the document should be
        /// saved before closing or not.
        /// </param>
        private void CloseOpenDocument(bool saveChanges)
        {
            if (this.wordProtector != null)
            {
                try
                {
                    this.application.DocumentBeforeClose -=
                        new Word.ApplicationEvents4_DocumentBeforeCloseEventHandler
                        (application_DocumentBeforeClose);
                    this.wordProtector.Close(saveChanges);
                }
                finally
                {
                    this.application.DocumentBeforeClose +=
                        new Word.ApplicationEvents4_DocumentBeforeCloseEventHandler
                        (application_DocumentBeforeClose);
                }
            }
        }

        /// <summary>
        /// Prompts the user asking if the currently open
        /// document should be saved before closing.
        /// </summary>
        /// <returns>
        /// Returns true if the user has indicated that it is safe
        /// to close the document that is currently open.  Otherwise,
        /// it returns false.
        /// </returns>
        private bool CanCloseDocument()
        {
            if (this.wordProtector == null)
                return true;

            DialogResult result = DialogResult.No;

            // If the document has been modified since it was last saved,
            // prompt the user asking if it should be saved before closing.
            if (this.wordProtector.IsDirty)
            {
                result = MessageBox.Show(String.Format(
                    System.Globalization.CultureInfo.CurrentCulture,
                    Properties.DocumentProtector.saveChangesText,
                    this.wordProtector.Name), this.Text,
                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
            }

            switch (result)
            {
                case DialogResult.Yes:
                    // Save the changes to the document.
                    this.SaveDocument();
                    return true;

                case DialogResult.Cancel:
                    // Do not close the document.
                    return false;
                case DialogResult.No:
                default:
                    // Do not save the changes to the document.
                    return true;
            }
        }

        /// <summary>
        /// Restores the current document to its last saved state.
        /// </summary>
        private void RevertDocument()
        {
            Debug.Assert(this.wordProtector != null);
            try
            {
                // Revert the document and rebuild the tree.
                this.application.DocumentBeforeClose -=
                    new Word.ApplicationEvents4_DocumentBeforeCloseEventHandler
                    (application_DocumentBeforeClose);
                this.wordProtector.Revert();
                this.BuildTree();

                // Ensure that the controls are properly set.
                // Document may have changed protection state
                // when it was reverted.
                this.SetDocumentControls(true);
            }
            catch
            {
                // In case there is no document any more,
                // set the controls to the current state.
                this.SetDocumentControls((this.wordProtector != null));
            }
            finally
            {
                this.application.DocumentBeforeClose +=
                    new Word.ApplicationEvents4_DocumentBeforeCloseEventHandler
                    (application_DocumentBeforeClose);
            }
        }

        #region Document Opening Methods
        /// <summary>
        /// Checks to see if the file is in a state that it can
        /// be opened by the tool.
        /// </summary>
        /// <param name="filename">The full path to the file to check.</param>
        /// <returns>
        /// Returns true if the file can be opened, false it it cannot.
        /// </returns>
        private static bool IsFileOpenSupported(string filename)
        {
            Debug.Assert(!String.IsNullOrEmpty(filename));
            Debug.Assert(File.Exists(filename));

            // Read-only documents are not supported.  Check to see
            // if this document is a read-only document.  If it is,
            // return false.
            if ((File.GetAttributes(filename) & FileAttributes.ReadOnly) ==
                FileAttributes.ReadOnly)
                return false;

            try
            {
                using (File.Open(filename, FileMode.Open,
                    FileAccess.ReadWrite, FileShare.None))
                {
                    // Try to open the document exclusively to verify
                    // that the document is not locked for editing.
                }
            }
            catch (IOException)
            {
                return false;
            }

            // Document is in an openable state.
            return true;
        }

        /// <summary>
        /// Opens the document at the specified path in Microsoft Word.
        /// </summary>
        /// <param name="filename">The full path of the file to open.</param>
        /// <returns>
        /// Returns a reference to the newly opened Word document.
        /// </returns>
        private Word.Document OpenDocumentInWord(string filename)
        {
            Debug.Assert(this.application != null);
            Debug.Assert(!String.IsNullOrEmpty(filename));
            Debug.Assert(File.Exists(filename));

            object missingValue = System.Reflection.Missing.Value;

            // SECURITY NOTE: The following code uses a hard-coded password 
            // to by-pass Word password protection.  Documents that actually 
            // use the following string as their password will not react
            // appropriately.
            object badPasswordValue = "badpassword";
            object filenameValue = filename as Object;
            object trueValue = true;
            object falseValue = false;
            Word.Document document = this.application.Documents.Open(
                ref filenameValue, ref falseValue, ref falseValue,
                ref falseValue, ref badPasswordValue, ref badPasswordValue,
                ref missingValue, ref badPasswordValue, ref badPasswordValue,
                ref missingValue, ref missingValue, ref falseValue, ref falseValue,
                ref trueValue, ref missingValue, ref missingValue);

            Debug.Assert(document != null);
            return document;
        }

        /// <summary>
        /// Opens the document at the specified path in Microsoft Word
        /// and populates the tree as appropriate.
        /// </summary>
        /// <param name="filename">The full path to the file to open.</param>
        internal void OpenNewDocument(string filename)
        {
            // Make sure a valid filename was specified.
            if (String.IsNullOrEmpty(filename) || (!File.Exists(filename)))
                throw new ArgumentException("filename");

            // Ensure that the file is one that can be opened
            // within the tool.
            if (IsFileOpenSupported(filename))
            {

                Word.Document document = null;
                try
                {
                    // Open the file in Word.
                    document = this.OpenDocumentInWord(filename);
                }
                catch(System.Runtime.InteropServices.COMException)
                {
                    // The new document could not be opened, correctly,
                    // so leave the form in its current state.
                    MessageBox.Show(
                        Properties.DocumentProtector.unsupportedFileText,
                        Properties.DocumentProtector.readOnlyDocument,
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                Debug.Assert(document != null);

                // Close the document currently open in the tool
                // if one exist without saving changes to it.  The
                // user should have been asked to save changes earlier
                // if they were necessary.
                this.CloseOpenDocument(false);

                this.wordProtector = new WordProtection.WordProtector(document);
                this.documentPassword =
                    DataProtection.ProtectData(String.Empty, this.Text);
                this.wordProtector.DocumentProtected += new EventHandler(wordProtector_DocumentProtected);
                this.wordProtector.DocumentUnprotected += new EventHandler(wordProtector_DocumentUnprotected);

                // A document was opened in the application,
                // so enable the controls required to interact
                // with the document and build its tree representation.
                this.SetDocumentControls(true);
                this.BuildTree();
            }
            else
            {
                // The application does not support opening the 
                // file that was specified, so ensure that the controls
                // required for documents are enabled if one is already
                // open.  Otherwise, disable them until a valid 
                // document is opened.
                this.SetDocumentControls((this.wordProtector != null));
                MessageBox.Show(
                    Properties.DocumentProtector.unsupportedFileText,
                    Properties.DocumentProtector.readOnlyDocument,
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        #endregion
        #region Document Level Protection Methods
        /// <summary>
        /// Toggles the current state of document protection.
        /// </summary>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -