Windows C# console程序中使用剪贴板取不到数据?

我想做的事情是开发一个console程序 打开指定Excel文件,通过 Microsoft.Office.Interop.Excel 的range copyPicture方法,将指定区域copy到剪贴板里,再输出一个jpg文件。

我的环境是 win10 VS2017,我using的相应类的引用都已经添加到了项目工程中,以下是我的代码:

`
using System;
using System.Windows.Forms;
using System.Drawing;
using Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApp1
{

class Program
{
    static void Main(string[] args)
    {

        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        Excel.Range range;

        string str;
        int rCnt = 0;
        int cCnt = 0;

        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Open(@"C:\Users\Public\Documents\testex.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        Excel.Range rg = xlWorkSheet.Range["A1:B2"];
        rg.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlBitmap);
        Console.WriteLine(rg);
        if (Clipboard.GetDataObject() != null) {
            IDataObject data = Clipboard.GetDataObject();
            Console.WriteLine(222);

            if (data.GetDataPresent(DataFormats.Bitmap)) {
                Console.WriteLine(333);
                Image image = (Image)data.GetData(DataFormats.Bitmap, true);
                image.Save(@"C:\Users\Public\Documents\testnb.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                Console.WriteLine(3444);
            }
        }
        Console.Read();
        
    }
}

}
`

我其实参考了这篇StackOverflow

但是当我的代码执行到 Clipboard.GetDataObject()这里时,剪贴板拿不到数据。

请教熟悉C#的朋友可以帮我看下吗?

阅读 4.8k
1 个回答

先确认一下你的 Program 类开头加上 [STAThread] 了吗?

没有就加一下,再看下好不好使。

如果还是不行,别用 Excel 库函数读剪贴板了,换 WinAPI 试一下,参考这篇:https://stackoverflow.com/que...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进