DarioSantarelli.Blog("UgiDotNet");

<sharing mode=”On” users=”*” />
posts - 176, comments - 105, trackbacks - 3

My Links

News


This is my personal blog. These postings are provided "AS IS" with no warranties, and confer no rights.




Tag Cloud

Archives

Post Categories

My English Blog

martedì 8 settembre 2009

Screenshots di Forms, Windows e schermo

Spesso in ambiente desktop può essere utile salvare degli screenshot relativi alla UI della nostra applicazione: in alcuni scenari ad esempio, oltre ai soliti log e trace, è molto comodo avere automaticamente lo screenshot dell’UI al momento dell’errore, magari come allegato di una email di report.
Una comune soluzione in Windows Forms è quella che sfrutta GDI+ tramite il metodo Graphics.CopyFromScreen(…) . In questo post vorrei mostrare come anche in WPF è possibile approfittare della stessa tecnica con il minimo sforzo: in particolare, nell’ helper class che segue sono presenti degli overload del metodo SaveScreenShot(…) per salvare su file system gli screenshot sia di singole Window (WPF) / Form (Windows Forms) che dell’intero schermo.


public class ScreenshotHelper
{
  // Per Windows Forms...
 
public static void SaveScreenShot(Form form, string fileName, ImageFormat imageFormat)
 
{
   
SaveScreenShot(form.Location, form.Size, fileName, imageFormat);
 
}

  // Per WPF... 
 
public static void SaveScreenShot(Window window, string fileName, ImageFormat imageFormat)
 
{
   
SaveScreenShot(new System.Drawing.Point((int)window.Left, (int)window.Top),
                  
new System.Drawing.Size((int)window.Width, (int)window.Height),
                  
fileName, imageFormat);
 
}

 
private static void SaveScreenShot(System.Drawing.Point windowLocation, System.Drawing.Size windowSize,
                                    
string fileName, ImageFormat imageFormat)
 
{                      
   
using (Bitmap bitmap = new Bitmap(windowSize.Width, windowSize.Height))
   
{
     
using (Graphics graphics = Graphics.FromImage(bitmap))
     
{
       
graphics.CopyFromScreen(windowLocation, new System.Drawing.Point(0, 0), windowSize);
     
}
     
bitmap.Save(fileName, imageFormat);
   
}
 


  // Schermo intero...
 
public static void SaveScreenShot(string fileName, ImageFormat imageFormat)
 
{
    
Rectangle bounds = Screen.GetBounds(System.Drawing.Point.Empty);
    
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
    
{
      
using (Graphics graphics = Graphics.FromImage(bitmap))
      
{
        
graphics.CopyFromScreen(System.Drawing.Point.Empty, System.Drawing.Point.Empty, bounds.Size);
      
}
      
bitmap.Save(fileName, imageFormat);
    
}
 
}
}


Nota: Questo metodo non riesce a catturare controlli trasparenti. Per gestirli occorre utilizzare altri metodi, nativi di GDI+, come mostrato in questo post.

Technorati Tag: ,,

posted @ lunedì 1 gennaio 0001 00:00 | Feedback (0) | Filed Under [ WPF ]

Powered by:
Powered By Subtext Powered By ASP.NET