PoshCode Logo PowerShell Code Repository

Take-Screenshot by Boe Prox 18 months ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2021"></script>download | new post

This script has a function that allows you to take a screenshot of the entire desktop or of an active window. Also includes option to save the screenshot to a file.

  1. Function Take-ScreenShot {
  2.     <#  
  3. .SYNOPSIS  
  4.     Used to take a screenshot of the desktop or the active window.
  5. .DESCRIPTION  
  6.     Used to take a screenshot of the desktop or the active window and save to an image file if needed.
  7. .PARAMETER screen
  8.     Screenshot of the entire screen
  9. .PARAMETER activewindow
  10.     Screenshot of the active window
  11. .PARAMETER file
  12.     Name of the file to save as. Default is image.bmp
  13. .PARAMETER imagetype
  14.     Type of image being saved. Can use JPEG,BMP,PNG. Default is bitmap(bmp)    
  15. .INPUTS
  16. .OUTPUTS    
  17. .NOTES  
  18.     Name: Take-ScreenShot
  19.     Author: Boe Prox
  20.     DateCreated: 07/25/2010    
  21. .EXAMPLE  
  22.     Take-ScreenShot -activewindow
  23.     Takes a screen shot of the active window        
  24. .EXAMPLE  
  25.     Take-ScreenShot -Screen
  26.     Takes a screenshot of the entire desktop
  27. .EXAMPLE  
  28.     Take-ScreenShot -activewindow -file "C:\image.bmp" -imagetype bmp
  29.     Takes a screenshot of the active window and saves the file named image.bmp with the image being bitmap
  30. .EXAMPLE  
  31.     Take-ScreenShot -screen -file "C:\image.png" -imagetype png    
  32.     Takes a screenshot of the entire desktop and saves the file named image.png with the image being png
  33. #>  
  34. #Requires -Version 2
  35.         [cmdletbinding(
  36.                 SupportsShouldProcess = $True,
  37.                 DefaultParameterSetName = "screen",
  38.                 ConfirmImpact = "low"
  39.         )]
  40. Param (
  41.        [Parameter(
  42.             Mandatory = $False,
  43.             ParameterSetName = "screen",
  44.             ValueFromPipeline = $True)]
  45.             [switch]$screen,
  46.        [Parameter(
  47.             Mandatory = $False,
  48.             ParameterSetName = "window",
  49.             ValueFromPipeline = $False)]
  50.             [switch]$activewindow,
  51.        [Parameter(
  52.             Mandatory = $False,
  53.             ParameterSetName = "",
  54.             ValueFromPipeline = $False)]
  55.             [string]$file,
  56.        [Parameter(
  57.             Mandatory = $False,
  58.             ParameterSetName = "",
  59.             ValueFromPipeline = $False)]
  60.             [string]
  61.             [ValidateSet("bmp","jpeg","png")]
  62.             $imagetype = "bmp"          
  63.        
  64. )
  65. # C# code
  66. $code = @'
  67. using System;
  68. using System.Runtime.InteropServices;
  69. using System.Drawing;
  70. using System.Drawing.Imaging;
  71. namespace ScreenShotDemo
  72. {
  73.  /// <summary>
  74.  /// Provides functions to capture the entire screen, or a particular window, and save it to a file.
  75.  /// </summary>
  76.  public class ScreenCapture
  77.  {
  78.    /// <summary>
  79.    /// Creates an Image object containing a screen shot the active window
  80.    /// </summary>
  81.    /// <returns></returns>
  82.    public Image CaptureActiveWindow()
  83.    {
  84.      return CaptureWindow( User32.GetForegroundWindow() );
  85.    }
  86.    /// <summary>
  87.    /// Creates an Image object containing a screen shot of the entire desktop
  88.    /// </summary>
  89.    /// <returns></returns>
  90.    public Image CaptureScreen()
  91.    {
  92.      return CaptureWindow( User32.GetDesktopWindow() );
  93.    }    
  94.    /// <summary>
  95.    /// Creates an Image object containing a screen shot of a specific window
  96.    /// </summary>
  97.    /// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
  98.    /// <returns></returns>
  99.    private Image CaptureWindow(IntPtr handle)
  100.    {
  101.      // get te hDC of the target window
  102.      IntPtr hdcSrc = User32.GetWindowDC(handle);
  103.      // get the size
  104.      User32.RECT windowRect = new User32.RECT();
  105.      User32.GetWindowRect(handle,ref windowRect);
  106.      int width = windowRect.right - windowRect.left;
  107.      int height = windowRect.bottom - windowRect.top;
  108.      // create a device context we can copy to
  109.      IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
  110.      // create a bitmap we can copy it to,
  111.      // using GetDeviceCaps to get the width/height
  112.      IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height);
  113.      // select the bitmap object
  114.      IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap);
  115.      // bitblt over
  116.      GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY);
  117.      // restore selection
  118.      GDI32.SelectObject(hdcDest,hOld);
  119.      // clean up
  120.      GDI32.DeleteDC(hdcDest);
  121.      User32.ReleaseDC(handle,hdcSrc);
  122.      // get a .NET image object for it
  123.      Image img = Image.FromHbitmap(hBitmap);
  124.      // free up the Bitmap object
  125.      GDI32.DeleteObject(hBitmap);
  126.      return img;
  127.    }
  128.    /// <summary>
  129.    /// Captures a screen shot of the active window, and saves it to a file
  130.    /// </summary>
  131.    /// <param name="filename"></param>
  132.    /// <param name="format"></param>
  133.    public void CaptureActiveWindowToFile(string filename, ImageFormat format)
  134.    {
  135.      Image img = CaptureActiveWindow();
  136.      img.Save(filename,format);
  137.    }
  138.    /// <summary>
  139.    /// Captures a screen shot of the entire desktop, and saves it to a file
  140.    /// </summary>
  141.    /// <param name="filename"></param>
  142.    /// <param name="format"></param>
  143.    public void CaptureScreenToFile(string filename, ImageFormat format)
  144.    {
  145.      Image img = CaptureScreen();
  146.      img.Save(filename,format);
  147.    }    
  148.  
  149.    /// <summary>
  150.    /// Helper class containing Gdi32 API functions
  151.    /// </summary>
  152.    private class GDI32
  153.    {
  154.      
  155.      public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter
  156.      [DllImport("gdi32.dll")]
  157.      public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest,
  158.        int nWidth,int nHeight,IntPtr hObjectSource,
  159.        int nXSrc,int nYSrc,int dwRop);
  160.      [DllImport("gdi32.dll")]
  161.      public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth,
  162.        int nHeight);
  163.      [DllImport("gdi32.dll")]
  164.      public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
  165.      [DllImport("gdi32.dll")]
  166.      public static extern bool DeleteDC(IntPtr hDC);
  167.      [DllImport("gdi32.dll")]
  168.      public static extern bool DeleteObject(IntPtr hObject);
  169.      [DllImport("gdi32.dll")]
  170.      public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject);
  171.    }
  172.  
  173.    /// <summary>
  174.    /// Helper class containing User32 API functions
  175.    /// </summary>
  176.    private class User32
  177.    {
  178.      [StructLayout(LayoutKind.Sequential)]
  179.      public struct RECT
  180.      {
  181.        public int left;
  182.        public int top;
  183.        public int right;
  184.        public int bottom;
  185.      }
  186.      [DllImport("user32.dll")]
  187.      public static extern IntPtr GetDesktopWindow();
  188.      [DllImport("user32.dll")]
  189.      public static extern IntPtr GetWindowDC(IntPtr hWnd);
  190.      [DllImport("user32.dll")]
  191.      public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);
  192.      [DllImport("user32.dll")]
  193.      public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect);
  194.      [DllImport("user32.dll")]
  195.      public static extern IntPtr GetForegroundWindow();      
  196.    }
  197.  }
  198. }
  199. '@
  200. #User Add-Type to import the code
  201. add-type $code -ReferencedAssemblies 'System.Windows.Forms','System.Drawing'
  202. #Create the object for the Function
  203. $capture = New-Object ScreenShotDemo.ScreenCapture
  204.  
  205. #Take screenshot of the entire screen
  206. If ($Screen) {
  207.     Write-Verbose "Taking screenshot of entire desktop"
  208.     #Save to a file
  209.     If ($file) {
  210.         If ($file -eq "") {
  211.             $file = "$pwd\image.bmp"
  212.             }
  213.         Write-Verbose "Creating screen file: $file with imagetype of $imagetype"
  214.         $capture.CaptureScreenToFile($file,$imagetype)
  215.         }
  216.     Else {
  217.         $capture.CaptureScreen()
  218.         }
  219.     }
  220. #Take screenshot of the active window    
  221. If ($ActiveWindow) {
  222.     Write-Verbose "Taking screenshot of the active window"
  223.     #Save to a file
  224.     If ($file) {
  225.         If ($file -eq "") {
  226.             $file = "$pwd\image.bmp"
  227.             }
  228.         Write-Verbose "Creating activewindow file: $file with imagetype of $imagetype"
  229.         $capture.CaptureActiveWindowToFile($file,$imagetype)
  230.         }
  231.     Else {
  232.         $capture.CaptureActiveWindow()
  233.         }    
  234.     }    
  235. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me