Questo sito utilizza cookies, anche di terze parti, per mostrare pubblicità e servizi in linea con il tuo account. Leggi l'informativa sui cookies.
Username: Password: oppure
C# / VB.NET - Avere uno screenshot della finestra attiva [c#]
Forum - C# / VB.NET - Avere uno screenshot della finestra attiva [c#]

Avatar
-MG- (Normal User)
Rookie


Messaggi: 37
Iscritto: 23/04/2011

Segnala al moderatore
Postato alle 21:13
Martedì, 03/07/2012
Salve, stavo cercando una guida su come mstrare in una picturebox lo screenshot del desktop. Il problema però si è rivelato un altro, infatti ho cpaito come fare, ma non è quello che mi interessa. Vorrei sapere quindi se esiste un modo di catturare solo la finestra attiva. Se non mi sono spiegato bene fatemelo sapere e grazie mille in anticipo.

PM Quote
Avatar
tasx (Dev Team)
Expert


Messaggi: 439
Iscritto: 15/12/2008

Segnala al moderatore
Postato alle 21:54
Martedì, 03/07/2012
Ciao!

ecco qua: http://lmgtfy.com/?q=winform+screenshot

ciaociao :k::k:


... sei un proxy che perde i pacchetti ...
PM Quote
Avatar
-MG- (Normal User)
Rookie


Messaggi: 37
Iscritto: 23/04/2011

Segnala al moderatore
Postato alle 22:21
Martedì, 03/07/2012
grazie, evidentemente era proprio la parola winform che mi avrebbe aperto tute le porte.
Comunque cercavo una guida, data una risposta così non è che abbia capito molto, comunque cercherò di trovare una spiegazione da solo come è giusto che sia, grazie mille ancora.

Ultima modifica effettuata da -MG- il 03/07/2012 alle 22:37
PM Quote
Avatar
pierotofy (Admin)
Guru^2


Messaggi: 6110
Iscritto: 04/12/2003

Segnala al moderatore
Postato alle 16:24
Venerdì, 06/07/2012
Questo potrebbe interessarti... l'ho scritto un po' di tempo fa:

ScreenshotTaker.cs
Codice sorgente - presumibilmente C#

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Drawing;
  6. using System.Windows.Forms;
  7. using System.Drawing.Imaging;
  8. using System.Diagnostics;
  9. using System.Runtime.InteropServices;
  10.  
  11. namespace PokerMuck
  12. {
  13.     public class ScreenshotTaker
  14.     {
  15.         /* PrintWindow: uses the PrintWindow function to take the screenshot. This is the best way to take a screenshot
  16.          *      as other windows around it will not cause overlapping, but it's not supported by applications that use OpenGL or
  17.          *      other libraries to do the canvas drawing
  18.          * PrintScreen: takes a normal screenshot (like you would by using the print screen key) and cuts it out using the size of the window */
  19.         public enum Mode { PrintWindow, PrintScreen };
  20.  
  21.         [DllImport("User32.dll", SetLastError = true)]
  22.         [return: MarshalAs(UnmanagedType.Bool)]
  23.         private static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);
  24.  
  25.         [DllImport("user32", EntryPoint = "SendMessageA")]
  26.         private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
  27.         const int WM_PRINT = 0x0317;
  28.         const uint WM_PRINTCLIENTONLY = 1;
  29.         const int WM_SETREDRAW = 0xB;
  30.  
  31.         public ScreenshotTaker()
  32.         {
  33.         }
  34.  
  35.         public Bitmap Take(){
  36.             Rectangle bounds = Screen.GetBounds(Point.Empty);
  37.             return Take(bounds);
  38.         }
  39.  
  40.         /* @param size: if different than window size, resizes the window before taking the screenshot
  41.          *    note that this is different than resizing a bitmap, we are literally changing the window size */
  42.         public Bitmap Take(Window window, bool clientOnly, Size size, Mode mode)
  43.         {
  44.             // We cannot use this method if the window is minimized
  45.             if (window.Minimized) return null;
  46.  
  47.             Size originalWindowSize = window.Size;
  48.             bool needResize = !originalWindowSize.Equals(size);
  49.  
  50.             try
  51.             {
  52.                 if (needResize)
  53.                 {
  54.                     // If we are taking the client only, we don't need the extra repaint
  55.                     window.Resize(size, clientOnly ? false : true);
  56.                 }
  57.  
  58.                 Rectangle screenshotRect = clientOnly ? window.ClientRectangle : window.Rectangle;
  59.  
  60.                 Bitmap result = new Bitmap(screenshotRect.Width, screenshotRect.Height, PixelFormat.Format24bppRgb);
  61.  
  62.                 if (mode == Mode.PrintWindow)
  63.                 {
  64.                     GetScreenshotUsingPrintWindow(window, clientOnly, result);
  65.                 }
  66.                 else if (mode == Mode.PrintScreen)
  67.                 {
  68.                     GetScreenshotUsingPrintScreen(window, clientOnly, result);
  69.                 }
  70.  
  71.  
  72.                 // Restore original dimension
  73.                 if (needResize)
  74.                 {
  75.                     window.Resize(originalWindowSize, true); // OK, repaint now!
  76.                 }
  77.  
  78.                 return result;
  79.             }
  80.             catch (Exception e)
  81.             {
  82.                 Trace.WriteLine("Failed to take screenshot of " + window.Title + ": " + e.Message);
  83.                 return null;
  84.             }
  85.         }
  86.  
  87.         private void GetScreenshotUsingPrintWindow(Window window, bool clientOnly, Bitmap buffer){
  88.             Graphics g = Graphics.FromImage(buffer);
  89.             IntPtr hdc = g.GetHdc();
  90.             uint nFlags = (clientOnly ? WM_PRINTCLIENTONLY : 0);
  91.             PrintWindow(window.Handle, hdc, nFlags);
  92.             g.ReleaseHdc(hdc);
  93.         }
  94.  
  95.         private void GetScreenshotUsingPrintScreen(Window window, bool clientOnly, Bitmap buffer)
  96.         {
  97.             Rectangle bounds = clientOnly ? window.ClientRectangle : window.Rectangle;
  98.             using (Graphics g = Graphics.FromImage(buffer))
  99.             {
  100.                 g.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size);
  101.             }
  102.         }
  103.  
  104.         public Bitmap Take(Window window, bool clientOnly, Mode mode = Mode.PrintScreen)
  105.         {
  106.             Rectangle rect = window.Rectangle;
  107.             Size winSize = new Size(rect.Width, rect.Height);
  108.  
  109.             return Take(window, clientOnly, winSize, mode);
  110.         }
  111.  
  112.         public Bitmap Take(Rectangle bounds)
  113.         {
  114.             Bitmap result = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format24bppRgb);
  115.             using (Graphics g = Graphics.FromImage(result))
  116.             {
  117.                 g.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size);
  118.             }
  119.  
  120.             return result;
  121.         }
  122.  
  123.         public static Bitmap Slice(Bitmap screenshot, Rectangle bounds)
  124.         {
  125.             if (screenshot == null) return null;
  126.  
  127.             Bitmap result = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format24bppRgb);
  128.             using (Graphics g = Graphics.FromImage(result))
  129.             {
  130.                 g.DrawImage(screenshot, 0, 0, bounds, GraphicsUnit.Pixel);
  131.             }
  132.  
  133.             return result;
  134.         }
  135.     }
  136. }



Window.cs
Codice sorgente - presumibilmente C++

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Runtime.InteropServices;
  6. using System.Drawing;
  7. using System.Diagnostics;
  8.  
  9. namespace PokerMuck
  10. {
  11.     /* This class helps us keep track of information about a specific window
  12.      * Plus it provides some nice static methods for Win32 windows handling */
  13.     public class Window
  14.     {
  15.         /* Get the text of a window */
  16.         [DllImport("user32.dll")]
  17.         public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
  18.  
  19.         /* Additionally we'll need this one to find the X-Y coordinate of the window */
  20.         [DllImport("user32.dll")]
  21.         [return: MarshalAs(UnmanagedType.Bool)]
  22.         public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
  23.  
  24.         [DllImport("user32.dll")]
  25.         [return: MarshalAs(UnmanagedType.Bool)]
  26.         public static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
  27.  
  28.         [DllImport("user32.dll")]
  29.         [return: MarshalAs(UnmanagedType.Bool)]
  30.         public static extern bool ClientToScreen(IntPtr hWnd, out POINT lpPoint);
  31.  
  32.         [DllImport("user32.dll")]
  33.         [return: MarshalAs(UnmanagedType.Bool)]
  34.         public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
  35.  
  36.  
  37.         /* We need also to define a RECT structure */
  38.         [StructLayout(LayoutKind.Sequential)]
  39.         public struct RECT
  40.         {
  41.             public int Left;        // x position of upper-left corner
  42.             public int Top;         // y position of upper-left corner
  43.             public int Right;       // x position of lower-right corner
  44.             public int Bottom;      // y position of lower-right corner
  45.         }
  46.  
  47.         /* And POINT */
  48.         [StructLayout(LayoutKind.Sequential)]
  49.         public struct POINT
  50.         {
  51.             public int x;
  52.             public int y;
  53.         }
  54.  
  55.         /* This one will help us detect when a window gets closed */
  56.         [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
  57.         public static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
  58.  
  59.         private IntPtr handle;
  60.         public IntPtr Handle { get { return (IntPtr)handle; } }
  61.  
  62.         // Keep track of the latest valid window title
  63.         private String latestValidWindowTitle = String.Empty;
  64.  
  65.         /* Returns the most current, valid window title
  66.          * An empty title is not a valid window title */
  67.         public String Title
  68.         {
  69.             get
  70.             {
  71.                 String newTitle = GetWindowTitleFromHandle(handle);
  72.                 if (newTitle != String.Empty) latestValidWindowTitle = newTitle;
  73.                 return latestValidWindowTitle;
  74.             }
  75.         }
  76.  
  77.         public Size Size
  78.         {
  79.             get{
  80.                 Rectangle rect = this.Rectangle;
  81.                 return new Size(rect.Width, rect.Height);
  82.             }
  83.         }
  84.  
  85.         public Rectangle Rectangle
  86.         {
  87.             get
  88.             {
  89.                 return GetWindowRectFromHandle(handle);
  90.             }
  91.         }
  92.  
  93.         /* Returns the rectangle in terms of absolute screen coordinates, not relative to the container */
  94.         public Rectangle ClientRectangle{
  95.             get
  96.             {
  97.                 return GetClientRectFromHandle(handle);
  98.             }
  99.         }
  100.  
  101.         public bool HasBeenMinimized { get; set; }
  102.  
  103.         public bool Minimized
  104.         {
  105.             get
  106.             {
  107.                 // On MS Windows, when a window is resized it is moved to -32000 both on X and Y coordinate
  108.                 // Is there a better way to code this?
  109.                 bool ret = (Rectangle.X == -32000 && Rectangle.Y == -32000);
  110.  
  111.                 // Keep track of the ever been minimized variable
  112.                 if (ret) HasBeenMinimized = true;
  113.  
  114.                 return ret;
  115.             }
  116.         }
  117.  
  118.  
  119.         /* User defined handle */
  120.         public Window(IntPtr handle)
  121.         {
  122.             this.handle = handle;
  123.             Initialize();
  124.         }
  125.  
  126.         /* Find the handle given the window title */
  127.         public Window(String windowTitle)
  128.         {
  129.             this.handle = Window.FindWindowByCaption(IntPtr.Zero, windowTitle);
  130.             Initialize();
  131.         }
  132.  
  133.         private void Initialize()
  134.         {
  135.             this.HasBeenMinimized = false;
  136.         }
  137.  
  138.         public bool Exists()
  139.         {
  140.             return Title != String.Empty && Exists(Title);
  141.         }
  142.  
  143.         public bool Resize(Size newSize, bool repaint = true)
  144.         {
  145.             return Window.ResizeWindow(handle, newSize, repaint);
  146.         }
  147.  
  148.  
  149.         // Static members
  150.  
  151.         public static bool Exists(String windowTitle)
  152.         {
  153.             return FindWindowByCaption(IntPtr.Zero, windowTitle) != IntPtr.Zero;
  154.         }
  155.  
  156.         public static String GetWindowTitleFromHandle(IntPtr handle)
  157.         {
  158.             const int maxChars = 256;
  159.             StringBuilder buffer = new StringBuilder(maxChars);
  160.             if (GetWindowText(handle, buffer, maxChars) > 0)
  161.             {
  162.                 return buffer.ToString();
  163.             }
  164.             else
  165.             {
  166.                 return "";
  167.             }
  168.         }
  169.  
  170.         public static bool ResizeWindow(IntPtr handle, Size newSize, bool repaint)
  171.         {
  172.             Rectangle windowRect = GetWindowRectFromHandle(handle);
  173.             return MoveWindow(handle, windowRect.X, windowRect.Y, newSize.Width, newSize.Height, repaint);
  174.         }
  175.  
  176.         public static Rectangle GetWindowRectFromWindowTitle(String windowTitle)
  177.         {
  178.             IntPtr handle = FindWindowByCaption(IntPtr.Zero, windowTitle);
  179.             return GetWindowRectFromHandle(handle);
  180.         }
  181.  
  182.         public static Rectangle GetClientRectFromHandle(IntPtr handle)
  183.         {
  184.             RECT rct; // C++ style
  185.             Rectangle clientRect = new Rectangle(); // C# style
  186.             if (GetClientRect(handle, out rct))
  187.             {
  188.                 // Translate to screen cordinates
  189.                 POINT topleft;
  190.                 topleft.x = rct.Left;
  191.                 topleft.y = rct.Top;
  192.  
  193.                 POINT bottomright;
  194.                 bottomright.x = rct.Right;
  195.                 bottomright.y = rct.Bottom;
  196.  
  197.                 ClientToScreen(handle, out topleft);
  198.                 ClientToScreen(handle, out bottomright);
  199.  
  200.                 clientRect.X = topleft.x;
  201.                 clientRect.Y = topleft.y;
  202.                 clientRect.Width = bottomright.x - topleft.x;
  203.                 clientRect.Height = bottomright.y - topleft.y;
  204.             }
  205.             else
  206.             {
  207.                 Trace.WriteLine("I couldn't figure out client position and size of window handle " + handle.ToString());
  208.             }
  209.  
  210.  
  211.  
  212.             return clientRect;
  213.         }
  214.  
  215.         public static Rectangle GetWindowRectFromHandle(IntPtr handle)
  216.         {
  217.             // Ok, let's figure out it's position
  218.  
  219.             RECT rct; // C++ style
  220.             Rectangle windowRect = new Rectangle(); // C# style
  221.             if (GetWindowRect(handle, out rct))
  222.             {
  223.                 windowRect.X = rct.Left;
  224.                 windowRect.Y = rct.Top;
  225.                 windowRect.Width = rct.Right - rct.Left;
  226.                 windowRect.Height = rct.Bottom - rct.Top;
  227.             }
  228.             else
  229.             {
  230.                 Trace.WriteLine("I couldn't figure out position and size of window handle " + handle.ToString());
  231.             }
  232.  
  233.             return windowRect;
  234.         }
  235.     }
  236. }



Seguimi su Twitter: http://www.twitter.com/pierotofy

Fai quello che ti piace, e fallo bene.
PM Quote