2

I would like to automatically save an image to file after I click "printscreen" but I don't know what I'm doing wrong.

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.PrintScreen)
        {
            Image screenshot = Clipboard.GetImage();
            screenshot.Save("c:\\Users\\Default\\Pictures\\screenshot.jpg");
        }
    }

The code doesn't contain any errors, it simply does not work as expected.

PaulG
  • 13,871
  • 9
  • 56
  • 78
Fanna1119
  • 1,878
  • 4
  • 24
  • 30
  • 1
    does it actually save the file? – Daniel A. White May 22 '13 at 15:07
  • is your form actually seleected? – Daniel A. White May 22 '13 at 15:07
  • 2
    Have you tried to set format, Like `screenshot.Save("c:\\Users\\Default\\Pictures\\screenshot.jpg", ImageFormat.Jpeg);` – Ilya Ivanov May 22 '13 at 15:07
  • I tried your code on a laptop with multiple set keys. The event didn't fire with the print key (which is also pos 1), but all other keys did. Did you try that your event is actually fired, for instance with a breakpoint? – Kai May 22 '13 at 15:21
  • 1
    I'm pretty sure printscreen gets trapped by OS itself and is consumed, therefore it would never reach the forms code. You could either: (1) Implement a low level keyboard hook and look for printscreen, or (2) Implement a Clipboard monitor so you known when an image has been placed there. – Idle_Mind May 22 '13 at 15:47
  • Hmmm...I was wrong. It was detected in the `KeyUp` event! *But if you want it to work when your application is NOT in focus, then my previous comment would apply. – Idle_Mind May 22 '13 at 15:53

4 Answers4

3

By default Save method saves in png format (compatible with bmp files, see examples in the tutorial), try to specify format of the image explicitly:

Image screenshot = Clipboard.GetImage();
screenshot.Save("c:\\Users\\Default\\Pictures\\screenshot.jpg", ImageFormat.Jpeg);
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
2

By default, the png encoder is used, not the jpg

http://msdn.microsoft.com/en-US/library/vstudio/ktx83wah.aspx

If you want to save as JPG, you have to use this overload

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
vc 74
  • 37,131
  • 7
  • 73
  • 89
0

You can always change the ImageFormat of course and copy from any source into Clipboard before.

item.SheetObject.CopyBitmapToClipboard();
Image img;
img = Clipboard.GetImage();
img.Save(temporaryFilePath + ".bmp", ImageFormat.Bmp);

But @Ilya Ivanov was correct too.

mike27015
  • 686
  • 1
  • 6
  • 19
0

Use the event KeyUp instead of KeyDown and also ImageFormat to save the picture in a correct way.

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.PrintScreen)
    {
        Image screenshot = Clipboard.GetImage();
        screenshot.Save("c:\\_temp\\screenshot.jpg", ImageFormat.Jpeg);
    }
}

Code works for me without problems and - of course - with a saved picture.

Kai
  • 1,953
  • 2
  • 13
  • 18