控制檯和mvc中使用webbrowser
用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);
}
}