Selection.CopyAsPicture 只是用来拷贝图片而不是将文字转化为图片

时间:2023-02-10 22:28:34

在工作中有客户问下面的代码为什么会返回false。

Word.Selection wdSelection = Application.Selection;
Clipboard.Clear();
Application.ActiveWindow.Selection
.SetRange(Application.ActiveDocument
.Bookmarks["\\Page"].Range.Start,
Application.ActiveDocument.Bookmarks["\\Page"].Range.End - 1);
Application.ActiveWindow.Selection.CopyAsPicture();
bool b = Clipboard.ContainsImage();
if (b)
MessageBox.Show("YES");
else
MessageBox.Show("NO");

我看了一下,原来客户的代码中

Application.ActiveDocument.Bookmarks["\\Page"].Range

是选择当前页(如果当前页只有一个图片时则报错)。所以对于纯文字CopyAsPicture和Copy是没有区别的(Clipboard.ContainsImage() 为false)。

如果当前页面上只有图片,那么Copy是要报错的。这里只能用CopyAsPicture(Clipboard.ContainsImage()为true)。

当文字与图片混排或有两个以上图片时 CopyAsPicture和Copy同样效果(Clipboard.ContainsImage() 为false)。

所以只用下面的代码会返回true。

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.Office.Tools.Word;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Office = Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;

namespace WordDocument14
{
    public partial class ThisDocument
    {
        private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
            Word.Selection wdSelection = Application.Selection;
            Clipboard.Clear();
            //注意确保整个文档中只有一张图片,没有其他东西。
            Application.ActiveWindow.Selection
                .SetRange(Application.ActiveDocument.Range().Start,
                Application.ActiveDocument.Range().End - 1);
            Application.ActiveWindow.Selection.Copy();
            bool b = Clipboard.ContainsImage();
            if (b)
                MessageBox.Show("YES");
            else
                MessageBox.Show("NO");
        }

        private void ThisDocument_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisDocument_Startup);
            this.Shutdown += new System.EventHandler(ThisDocument_Shutdown);
        }

        #endregion
    }
}