此代码出自CSDNhttp://download.csdn.net/source/1383175我对代码进行了一些简单的分析如下:
public Form1() { InitializeComponent(); //先定义控件的DocumentCompleted事件,网页加载完毕 //System.Windows.Forms.WebBrowser this.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); } /// <summary> /// 委托事件,网页加载完就触发 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { GetImage(); } void GetImage() { if (webBrowser1.Document == null) return; try { //得到网页的高度 int scrollHeight = webBrowser1.Document.Body.ScrollRectangle.Height; //得到网页的宽度 int scrollWidth = webBrowser1.Document.Body.ScrollRectangle.Width; //重新设置控件的大小 webBrowser1.Size = new Size(scrollWidth, scrollHeight); //创造一个空图片 Bitmap bm = new Bitmap(scrollWidth, scrollHeight); //把控件画到这个图片中去 webBrowser1.DrawToBitmap(bm, new Rectangle(0, 0, bm.Width, bm.Height)); //制造一个文件名 string saveAsName; saveAsName = Regex.Replace(txtURL.Text, @"(\\|\/|\:|\*|\?|\""|\<|\>|\|)?", ""); //按这个文件名保存图片 bm.Save(saveAsName + ".png", System.Drawing.Imaging.ImageFormat.Png); //释放这个图片 bm.Dispose(); } catch (Exception e) { MessageBox.Show(e.Message, "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { } btnOK.Enabled = true; } private void buttonCapture_Click(object sender, EventArgs e) { //开始加载一个网页,加载完了就执行委托事件 webBrowser1.Navigate(txtURL.Text); btnOK.Enabled = false; }
如需下载请去文上所提到的连接中下载