Capture d’écran de la fenêtre active?

Je fais une application de capture d’écran et tout se passe bien. Tout ce que j’ai à faire est de capturer la fenêtre active et de prendre une capture d’écran de cette fenêtre active. Est-ce que quelqu’un sait comment je peux le faire?

ScreenCapture sc = new ScreenCapture(); // capture entire screen, and save it to a file Image img = sc.CaptureScreen(); // display image in a Picture control named imageDisplay this.imageDisplay.Image = img; // capture this window, and save it sc.CaptureWindowToFile(this.Handle,"C:\\temp2.gif",ImageFormat.Gif); 

http://www.developerfusion.com/code/4630/capture-a-screen-shot/

 Rectangle bounds = Screen.GetBounds(Point.Empty); using(Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height)) { using(Graphics g = Graphics.FromImage(bitmap)) { g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size); } bitmap.Save("test.jpg", ImageFormat.Jpeg); } 

pour capturer l’utilisation actuelle de la fenêtre

  Rectangle bounds = this.Bounds; using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.CopyFromScreen(new Point(bounds.Left,bounds.Top), Point.Empty, bounds.Size); } bitmap.Save("C://test.jpg", ImageFormat.Jpeg); } 

Je suggère la solution suivante pour capturer toute fenêtre active actuelle (pas seulement notre application C #) ou un écran entier avec la détermination de la position du curseur par rapport au coin supérieur gauche de la fenêtre ou de l’écran respectivement:

 public enum enmScreenCaptureMode { Screen, Window } class ScreenCapturer { [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect); [StructLayout(LayoutKind.Sequential)] private struct Rect { public int Left; public int Top; public int Right; public int Bottom; } public Bitmap Capture(enmScreenCaptureMode screenCaptureMode = enmScreenCaptureMode.Window) { Rectangle bounds; if (screenCaptureMode == enmScreenCaptureMode.Screen) { bounds = Screen.GetBounds(Point.Empty); CursorPosition = Cursor.Position; } else { var foregroundWindowsHandle = GetForegroundWindow(); var rect = new Rect(); GetWindowRect(foregroundWindowsHandle, ref rect); bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); CursorPosition = new Point(Cursor.Position.X - rect.Left, Cursor.Position.Y - rect.Top); } var result = new Bitmap(bounds.Width, bounds.Height); using (var g = Graphics.FromImage(result)) { g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); } return result; } public Point CursorPosition { get; protected set; } } 

Voici un extrait pour capturer le bureau ou la fenêtre active. Il ne fait aucune référence à Windows Forms.

 public class ScreenCapture { [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] public static extern IntPtr GetDesktopWindow(); [StructLayout(LayoutKind.Sequential)] private struct Rect { public int Left; public int Top; public int Right; public int Bottom; } [DllImport("user32.dll")] private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect); public static Image CaptureDesktop() { return CaptureWindow(GetDesktopWindow()); } public static Bitmap CaptureActiveWindow() { return CaptureWindow(GetForegroundWindow()); } public static Bitmap CaptureWindow(IntPtr handle) { var rect = new Rect(); GetWindowRect(handle, ref rect); var bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); var result = new Bitmap(bounds.Width, bounds.Height); using (var graphics = Graphics.FromImage(result)) { graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); } return result; } } 

Comment capturer tout l’écran:

 var image = ScreenCapture.CaptureDesktop(); image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg); 

Comment capturer la fenêtre active:

 var image = ScreenCapture.CaptureActiveWindow(); image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg); 

Initialement trouvé ici: http://www.snippetsource.net/Snippet/158/capture-screenshot-in-c

Le code de KvanTTT a bien fonctionné. Je l’ai un peu allongé pour permettre un peu plus de flexibilité sur le format de sauvegarde, ainsi que la possibilité d’enregistrer avec hWnd, .NET Control / Form. Vous pouvez obtenir un bitmap ou enregistrer dans un fichier, avec quelques options.

 using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; namespace MosaiqPerformanceMonitor { public enum CaptureMode { Screen, Window } public static class ScreenCapturer { [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect); [StructLayout(LayoutKind.Sequential)] private struct Rect { public int Left; public int Top; public int Right; public int Bottom; } [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] public static extern IntPtr GetDesktopWindow(); ///  Capture Active Window, Desktop, Window or Control by hWnd or .NET Contro/Form and save it to a specified file.  /// Filename. /// * If extension is omitted, it's calculated from the type of file /// * If path is omitted, defaults to %TEMP% /// * Use %NOW% to put a timestamp in the filename /// Optional. The default value is CaptureMode.Window. /// Optional file save mode. Default is PNG public static void CaptureAndSave(ssortingng filename, CaptureMode mode = CaptureMode.Window, ImageFormat format = null) { ImageSave(filename, format, Capture(mode)); } ///  Capture a specific window (or control) and save it to a specified file.  /// Filename. /// * If extension is omitted, it's calculated from the type of file /// * If path is omitted, defaults to %TEMP% /// * Use %NOW% to put a timestamp in the filename /// hWnd (handle) of the window to capture /// Optional file save mode. Default is PNG public static void CaptureAndSave(ssortingng filename, IntPtr handle, ImageFormat format = null) { ImageSave(filename, format, Capture(handle)); } ///  Capture a specific window (or control) and save it to a specified file.  /// Filename. /// * If extension is omitted, it's calculated from the type of file /// * If path is omitted, defaults to %TEMP% /// * Use %NOW% to put a timestamp in the filename /// Object to capture /// Optional file save mode. Default is PNG public static void CaptureAndSave(ssortingng filename, Control c, ImageFormat format = null) { ImageSave(filename, format, Capture(c)); } ///  Capture the active window (default) or the desktop and return it as a bitmap  /// Optional. The default value is CaptureMode.Window. public static Bitmap Capture(CaptureMode mode = CaptureMode.Window) { return Capture(mode == CaptureMode.Screen ? GetDesktopWindow() : GetForegroundWindow()); } ///  Capture a .NET Control, Form, UserControl, etc.  /// Object to capture ///  Bitmap of control's area  public static Bitmap Capture(Control c) { return Capture(c.Handle); } ///  Capture a specific window and return it as a bitmap  /// hWnd (handle) of the window to capture public static Bitmap Capture(IntPtr handle) { Rectangle bounds; var rect = new Rect(); GetWindowRect(handle, ref rect); bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); CursorPosition = new Point(Cursor.Position.X - rect.Left, Cursor.Position.Y - rect.Top); var result = new Bitmap(bounds.Width, bounds.Height); using (var g = Graphics.FromImage(result)) g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); return result; } ///  Position of the cursor relative to the start of the capture  public static Point CursorPosition; ///  Save an image to a specific file  /// Filename. /// * If extension is omitted, it's calculated from the type of file /// * If path is omitted, defaults to %TEMP% /// * Use %NOW% to put a timestamp in the filename /// Optional file save mode. Default is PNG /// Image to save. Usually a BitMap, but can be any /// Image. static void ImageSave(ssortingng filename, ImageFormat format, Image image) { format = format ?? ImageFormat.Png; if (!filename.Contains(".")) filename = filename.Trim() + "." + format.ToSsortingng().ToLower(); if (!filename.Contains(@"\")) filename = Path.Combine(Environment.GetEnvironmentVariable("TEMP") ?? @"C:\Temp", filename); filename = filename.Replace("%NOW%", DateTime.Now.ToSsortingng("yyyy-MM-dd@hh.mm.ss")); image.Save(filename, format); } } } 

Je suppose que vous utilisez Graphics.CopyFromScreen pour obtenir la capture d’écran.

Vous pouvez utiliser P / Invoke pour GetForegroundWindow ( puis obtenir sa position et sa taille ) pour déterminer la région à copier.

Vous pouvez utiliser le code de cette question: Comment enregistrer une capture d’écran directement dans un fichier sous Windows?

Il vous suffit de remplacer WIN32_API.GetDesktopWindow() par la propriété Handle de la fenêtre que vous souhaitez capturer.

Une petite modification de la méthode statique void ImageSave () vous accordera l’option pour l’enregistrer. Le crédit va à Microsoft (http://soffr.miximages.com/c%23/ppre codestatic void ImageSave(ssortingng filename, ImageFormat format, Image image, SaveFileDialog saveFileDialog1) { saveFileDialog1.Filter = JPeg Image.jpg|Bitmap Image|*.bmp|Gif Image|*.gif”; saveFileDialog1.Title = “Enregistrer un image”; saveFileDialog1.ShowDialog(); // If the file name is not an empty ssortingng open it for saving. if (saveFileDialog1.FileName != “”) { // Saves the Image via a FileStream created by the OpenFile method. System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile(); // Saves the Image in the appropriate ImageFormat based upon the // File type selected in the dialog box. // NOTE that the FilterIndex property is one-based. switch (saveFileDialog1.FilterIndex) { case 1: image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg); break; case 2: image.Save(fs, System.Drawing.Imaging.ImageFormat.Bmp); break; case 3: image.Save(fs, System.Drawing.Imaging.ImageFormat.Gif); break; } fs.Close(); } }

Votre événement button_click doit être codé comme ceci …

 private void btnScreenShot_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); ScreenCapturer.CaptureAndSave(filename, mode, format, saveFileDialog1); }// 

Si vous souhaitez utiliser le code managé: Cela capturera toute fenêtre via le ProcessId.

J’ai utilisé ce qui suit pour rendre la fenêtre active.

 Microsoft.VisualBasic.Interaction.AppActivate(ProcessId); Threading.Thread.Sleep(20); 

J’ai utilisé l’écran d’impression pour capturer une fenêtre.

 SendKeys.SendWait("%{PRTSC}"); Threading.Thread.Sleep(40); IDataObject objData = Clipboard.GetDataObject(); 

Utilisez le code suivant:

  // Shot size = screen size Size shotSize = Screen.PrimaryScreen.Bounds.Size; // the upper left point in the screen to start shot // 0,0 to get the shot from upper left point Point upperScreenPoint = new Point(0, 0); // the upper left point in the image to put the shot Point upperDestinationPoint = new Point(0, 0); // create image to get the shot in it Bitmap shot = new Bitmap(shotSize.Width, shotSize.Height); // new Graphics instance Graphics graphics = Graphics.FromImage(shot); // get the shot by Graphics class graphics.CopyFromScreen(upperScreenPoint, upperDestinationPoint, shotSize); // return the image pictureBox1.Image = shot; 

Basé sur la réponse d’ArsenMkrt, mais celui-ci vous permet de capturer un contrôle dans votre formulaire (j’écris par exemple un outil qui a un contrôle WebBrowser et qui veut capturer uniquement son affichage). Notez l’utilisation de la méthode PointToScreen:

 //Project: WebCapture //Filename: ScreenshotUtils.cs //Author: George Birbilis (http://zoomicon.com) //Version: 20130820 using System.Drawing; using System.Windows.Forms; namespace WebCapture { public static class ScreenshotUtils { public static Rectangle Offseted(this Rectangle r, Point p) { r.Offset(p); return r; } public static Bitmap GetScreenshot(this Control c) { return GetScreenshot(new Rectangle(c.PointToScreen(Point.Empty), c.Size)); } public static Bitmap GetScreenshot(Rectangle bounds) { Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height); using (Graphics g = Graphics.FromImage(bitmap)) g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); return bitmap; } public const ssortingng DEFAULT_IMAGESAVEFILEDIALOG_TITLE = "Save image"; public const ssortingng DEFAULT_IMAGESAVEFILEDIALOG_FILTER = "PNG Image (*.png)|*.png|JPEG Image (*.jpg)|*.jpg|Bitmap Image (*.bmp)|*.bmp|GIF Image (*.gif)|*.gif"; public const ssortingng CUSTOMPLACES_COMPUTER = "0AC0837C-BBF8-452A-850D-79D08E667CA7"; public const ssortingng CUSTOMPLACES_DESKTOP = "B4BFCC3A-DB2C-424C-B029-7FE99A87C641"; public const ssortingng CUSTOMPLACES_DOCUMENTS = "FDD39AD0-238F-46AF-ADB4-6C85480369C7"; public const ssortingng CUSTOMPLACES_PICTURES = "33E28130-4E1E-4676-835A-98395C3BC3BB"; public const ssortingng CUSTOMPLACES_PUBLICPICTURES = "B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5"; public const ssortingng CUSTOMPLACES_RECENT = "AE50C081-EBD2-438A-8655-8A092E34987A"; public static SaveFileDialog GetImageSaveFileDialog( ssortingng title = DEFAULT_IMAGESAVEFILEDIALOG_TITLE, ssortingng filter = DEFAULT_IMAGESAVEFILEDIALOG_FILTER) { SaveFileDialog dialog = new SaveFileDialog(); dialog.Title = title; dialog.Filter = filter; /* //this seems to throw error on Windows Server 2008 R2, must be for Windows Vista only dialog.CustomPlaces.Add(CUSTOMPLACES_COMPUTER); dialog.CustomPlaces.Add(CUSTOMPLACES_DESKTOP); dialog.CustomPlaces.Add(CUSTOMPLACES_DOCUMENTS); dialog.CustomPlaces.Add(CUSTOMPLACES_PICTURES); dialog.CustomPlaces.Add(CUSTOMPLACES_PUBLICPICTURES); dialog.CustomPlaces.Add(CUSTOMPLACES_RECENT); */ return dialog; } public static void ShowSaveFileDialog(this Image image, IWin32Window owner = null) { using (SaveFileDialog dlg = GetImageSaveFileDialog()) if (dlg.ShowDialog(owner) == DialogResult.OK) image.Save(dlg.FileName); } } } 

Avoir l’object Bitmap que vous pouvez simplement appeler Enregistrer dessus

 private void btnCapture_Click(object sender, EventArgs e) { webBrowser.GetScreenshot().Save("C://test.jpg", ImageFormat.Jpeg); } 

Ce qui précède suppose que le GC récupère le bitmap, mais peut-être est-il préférable d’atsortingbuer le résultat de someControl.getScreenshot () à une variable Bitmap, puis de supprimer cette variable manuellement, surtout si vous le faites souvent une liste de pages Web que vous souhaitez charger et en enregistrer des captures d’écran):

 private void btnCapture_Click(object sender, EventArgs e) { Bitmap bitmap = webBrowser.GetScreenshot(); bitmap.ShowSaveFileDialog(); bitmap.Dispose(); //release bitmap resources } 

Mettre à jour:

Désormais, l’outil WebCapture est déployé par ClickOnce ( http://gallery.clipflair.net/WebCapture ) à partir du Web (possède également un bon support de mise à jour automatique grâce à ClickOnce) et vous pouvez trouver son code source à l’ adresse http://ClipFlair.codeplex.com .