Hello Everyone,
I'm a new poster here and apologize in advance if I have posted this in the wrong subforum.
I am trying to use Visual Studio C# to printscreen, then save the screen capture to a file.
Currently, I am having problems reading from the clipboard. I have tried using both of the following lines to save a screen capture to the clipboard:
SendKeys.SendWait("+{PRTSC}");
SendKeys.SendWait("{PRTSC}");
However, when I try to save the image using the following lines, I get a Null Reference Exception.
image = (Image)Clipboard.GetDataObject().GetData(DataFormats.Bitmap);
image.Save("image.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
I have tested if the clipboard actually contains an image, and the following lines indicate that it thinks the clipboard is empty. i.e. the program writes "Clipboard empty."
if (Clipboard.GetDataObject() == null)
{
Console.WriteLine("Clipboard empty.");
}
However, I know that it is not empty since I can paste the screen capture to paint after running the code.
I have looked at many tutorials on how to save screenshots to image files and don't know what I am doing wrong here. Any help would be much appreciated.
Thanks!
Loading
孙卓识 孙卓识Posted Sep 25, 2021, 9:58 AM
I've suffered from the same issue, access clipboard in C# requires a STA thread.
You may try code like this:
You can find more detail info here:
https://softwareengineering.stackexchange.com/questions/304742/why-does-the-windows-clipboard-require-an-sta-thread
Hemant SrivastavaPosted May 31, 2013, 11:27 AM
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.");
}