为什么我的应用程序告诉我我的剪贴板显示为空时显然不是?

Goo*_*son 0 .net c# clipboard screenshot console-application

我试图用控制台应用程序截取我的屏幕截图,然后将其保存到我的桌面但由于某种原因..它告诉我,我的剪贴板是空的时候显然它不是..如果你检查代码你可以看到我按PrintScreen,当您这样做时,它会将其保存到剪贴板.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace ScreenshotConsole
{
    class Program
    {

        static void Main(string[] args)
        {
            screenshot();
            Console.WriteLine("Printescreened");
            saveScreenshot();
            Console.ReadLine();
        }


        static void screenshot()
        {
            SendKeys.SendWait("{PRTSC}");
        }

        static void saveScreenshot()
        {
            //string path;
            //path = "%AppData%\\Sys32.png"; // collection of paths
            //path = Environment.ExpandEnvironmentVariables(path);

            if (Clipboard.ContainsImage() == true)
            {
                Image image = (Image)Clipboard.GetDataObject().GetData(DataFormats.Bitmap);
                image.Save("image.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                Console.WriteLine("Clipboard empty.");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

WAK*_*AKU 5

屏幕截图需要一些时间,因此您在按下后会添加延迟{PRTSC}:

static void screenshot()
{
    SendKeys.SendWait("{PRTSC}");
    Thread.Sleep(500);
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

好的,我想通了,添加STAThreadAttribute到你的主要方法:

    [STAThread]
    static void Main(string[] args)
    {
        screenshot();
        Console.WriteLine("Printescreened");
        saveScreenshot();
        Console.ReadLine();
    }
Run Code Online (Sandbox Code Playgroud)

MSDN说:

Clipboard类只能在设置为单线程单元(STA)模式的线程中使用.要使用此类,请确保使用STAThreadAttribute属性标记Main方法.

更多详情