wxpython-users Digest, Vol 1, Issue 2

Now that it is in the clipboard, what are you going to do with it?
This code was posted a few weeks ago- It will take a screenshot and
save that image to a bmp file.

----------------------------------------------------------------------

Message: 1
Date: Fri, 21 Mar 2008 23:45:46 +0100
From: Stef Mientki <s.mientki@ru.nl>
Subject: Re: [wxPython-users] Re: How to copy a Frame or Window to the
        clipboard ?
To: wxPython-users@lists.wxwidgets.org
Message-ID: <47E43A9A.6050606@ru.nl>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Without realizing until now, I just answered the question myself :wink:
      SendKeys.SendKeys ( '%{PRTSC}' )

cheers,
Stef

def TakeScreenShot(self, rect):
      """ Takes a screenshot of the screen at give pos & size (rect). """

      #Create a DC for the whole screen area
      dcScreen = wx.ScreenDC()

      #Create a Bitmap that will later on hold the screenshot image
      #Note that the Bitmap must have a size big enough to hold the screenshot
      #-1 means using the current default colour depth
      bmp = wx.EmptyBitmap(rect.width, rect.height)

      #Create a memory DC that will be used for actually taking the screenshot
      memDC = wx.MemoryDC()

      #Tell the memory DC to use our Bitmap
      #all drawing action on the memory DC will go to the Bitmap now
      memDC.SelectObject(bmp)

      #Blit (in this case copy) the actual screen on the memory DC
      #and thus the Bitmap
      memDC.Blit( 0, #Copy to this X coordinate
          0, #Copy to this Y coordinate
          rect.width, #Copy this width
          rect.height, #Copy this height
          dcScreen, #From where do we copy?
          rect.x, #What's the X offset in the original DC?
          rect.y #What's the Y offset in the original DC?
          )

      #Select the Bitmap out of the memory DC by selecting a new
      #uninitialized Bitmap
      memDC.SelectObject(wx.NullBitmap)

      return bmp

And then, for the widget you want to take the screenshot (it can be
also the main frame), you can do something like:

bmp = self.TakeScreenShot(self.GetRect())
img = bmp.ConvertToImage()
fileName = "myImage.png"
img.SaveFile(fileName, wx.BITMAP_TYPE_PNG)