This article describes how to obtain a webpage through the webbroswer control in winform. This method can capture webpages larger than the screen area, but the images cannot be obtained by flash or some controls on the webpage. Because it is a winform control, it is not tested in WPF.
Add a text box and a button to the interface. The text box is used to enter the address. Initialize a webbrowser In the event processing function pressed by the button and open the webpage, but it is not displayed on the interface.
1 /// <Summary>
2 /// Button pressing event processing function
3 /// </Summary>
4 /// <Param name = "sender"> </param>
5 /// <Param name = "E"> </param>
6 Private Void Savesnapshot_click ( Object Sender, eventargs E)
7 {
8 Webbrowser = New Webbrowser (); // Create a webbrowser
9 Webbrowser. scrollbarsenabled = False ; // Hide a scroll bar
10 Webbrowser. navigate (address. Text ); // Open webpage
11 Webbrowser. documentcompleted + = New Webbrowserdocumentcompletedeventhandler (webbrowser_documentcompleted ); // Added the event processing function for webpage loading.
12 }
Obtain the image from the processing function after the webpage is loaded, adjust the image size, and save it.
1 /// <Summary>
2 /// Webpage loading completion event processing function
3 /// </Summary>
4 /// <Param name = "sender"> </param>
5 /// <Param name = "E"> </param>
6 Void Webbrowser_documentcompleted ( Object Sender, webbrowserdocumentcompletedeventargs E)
7 {
8 Webbrowser = (Webbrowser) sender;
9
10 // The webpage is saved after being loaded.
11 If (Webbrowser. readystate = Webbrowserreadystate. Complete)
12 {
13 // You can also set the webpage height and width.
14 Int Height = Webbrowser. Document. Body. scrollrectangle. height;
15 Int Width = Webbrowser. Document. Body. scrollrectangle. width;
16
17 // Adjust the height and width of webbrowser
18 Webbrowser. Height = Height;
19 Webbrowser. Width = Width;
20
21 Bitmap bitmap = New Bitmap (width, height ); // Create an image with the same height and width as the webpage
22 Rectangle rectangle = New Rectangle ( 0 , 0 , Width, height ); // Drawing Area
23 Webbrowser. drawtobitmap (bitmap, rectangle ); //
24
25 // Save image dialog box
26 Savefiledialog = New Savefiledialog ();
27 Savefiledialog. Filter = " JPEG (*. jpg) | *. jpg | PNG (*. PNG) | *. PNG " ;
28 Savefiledialog. showdialog ();
29
30 Bitmap. Save (savefiledialog. filename ); // Save image
31 }
32 }
Sample download (Visual Studio 2010)