C# Get Desktop Screenshot ZZ

I found this feature while looking inside Graphics class and since it was so simple to use, I decided to post it here.

As I said, it doesn't require more than 15 lines of code - this function: Graphics.CopyFromScreen does all the 'hard work' so we only need to put this into a Bitmap and save/display it.

To the code!



There are 3 steps that you need to follow:

  • create a Bitmap that's exactly the screen's size
  • using that Bitmap, create a Graphics object (Graphics.FromImage)
  • use CopyFromScreen() and save the Bitmap



The code looks like this:

    1. private void takeScreenShot()
    2. {
    3. Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
    4. using (Graphics g = Graphics.FromImage(bmp))
    5. {
    6. g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
    7. bmp.Save("screenshot.png"); // saves the image
    8. }
    9. }
原文地址:https://www.cnblogs.com/zeroone/p/3378784.html