DotNet Screenshot

Dot Net WebBrowser control screenshots

One of my side projects consists of taking screenshots of webpages. The application I have created is a WinForm application in .Net 7, I have been using DrawToBitmap() method, and this works fine for some controls. … but not for the WebView Control ! HEre is the solution I have found to solve the issue.

System.Drawing.Graphics class

The code below takes a screenshot of an area of the screen. The trick is to make the area match with the control you want to take the picture of. In my case, pCapture is the control containing everything I want to get in the Picture. The PointToScreen() method gives me the absolute coordinate of the pCapture Control.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
       ...
           Size size = pCapture.Size;
           using (Bitmap bitmap = new Bitmap(size.Width, size.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555))
           using (Graphics memoryGraphics = Graphics.FromImage(bitmap))
           {
               MemoryStream stream = new MemoryStream();

               // Retrieves the control coordinates on the screen
               Point origin = pCapture.PointToScreen(new Point(0, 0));
               Int32 screenX = origin.X;
               Int32 screenY = origin.Y;

               memoryGraphics.CopyFromScreen(screenX, screenY, 0, 0, size);

               string filepath = Path.Combine(this.defaultFolder, DateTime.Now.ToString("yyyy-MM-dd-HHmmss") + "-shot.png");
               bitmap.Save(filepath, ImageFormat.Png);
           }
       ...

References