Search code examples
c#.netconsole-applicationscreenshotclipboard

Why is my application telling me that my clipboard is empty when clearly it's not?


Im trying to take a screenshot of my screen with a console application and then save it to my desktop but for some reason.. its telling me that my clipboard is empty when clearly its not.. If you check the code you can see that I press PrintScreen and when you do that it saves it to the clipboard.

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.");
            }
        }
    }
}

Solution

  • It will take some time to screenshot, so you shoud add a delay after pressing {PRTSC}:

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

    UPDATE

    OK, I figured it out, add STAThreadAttribute to your main method:

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

    MSDN says that:

    The Clipboard class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.

    More detail