用webbrowser主要是为了截屏
但必须注意的是,用webbrowser必须在一个所谓的叫单一线程单元的线程中执行,一般你直接 new webbrowser会报错的
控制台程序,在main上加个[STAThread]
class Program
{
static System.Windows.Forms.WebBrowser wb;
[STAThread]
static void Main(string[] args)
{
wb = new System.Windows.Forms.WebBrowser();
wb.DocumentCompleted += wb_DocumentCompleted;
wb.Navigate("http://10.5.10.143:9091/");
Console.Out.Write(wb.DocumentText);
while (wb.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents(); //避免假死,若去掉则可能无法触发 DocumentCompleted 事件。
}
}
static void wb_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
//设置浏览器宽度、高度为文档宽度、高度,以便截取整个网页。
wb.Width = wb.Document.Body.ScrollRectangle.Width;
wb.Height = wb.Document.Body.ScrollRectangle.Height;
using (Bitmap bmp = new Bitmap(wb.Width, wb.Height))
{
wb.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.Save("C:\\Capture.png", ImageFormat.Png);
}
}
}
mvc 开个新线程去new webbrowser给线程属性 t.SetApartmentState(ApartmentState.STA);
public void ss()
{
System.Threading.Thread t = new System.Threading.Thread(new ThreadStart(() => {
wb = new System.Windows.Forms.WebBrowser();
wb.DocumentCompleted += wb_DocumentCompleted;
wb.Navigate("http://10.5.10.143:9091/");
while (wb.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents(); //避免假死,若去掉则可能无法触发 DocumentCompleted 事件。
}
})
);
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
void wb_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
//设置浏览器宽度、高度为文档宽度、高度,以便截取整个网页。
wb.Width = wb.Document.Body.ScrollRectangle.Width;
wb.Height = wb.Document.Body.ScrollRectangle.Height;
using (Bitmap bmp = new Bitmap(wb.Width, wb.Height))
{
wb.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.Save("C:\\Capture1.png", ImageFormat.Png);
}
}