using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading; using System.Windows.Forms; using AshMind.Web.Snapshots.Sizing; // This code was built using information from an article // "Build A Self-Caching ASP.NET Web Site Thumbnail Control" by Peter Bromberg // http://www.eggheadcafe.com/tutorials/aspnet/b7cce396-e2b3-42d7-9571-cdc4eb38f3c1/build-a-selfcaching-asp.aspx namespace AshMind.Web.Snapshots { public static class WebSnapshot { public static Image Create(Uri url, IWebSnapshotSize size) { if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { Image image = null; RunInSTAThread(() => image = RequestSnapshot(url, size)); return image; } return RequestSnapshot(url, size); } private static void RunInSTAThread(ThreadStart action) { var thread = new Thread(action) { Name = "WebSnapshot.BrowserThread", IsBackground = true }; thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); } private static Image RequestSnapshot(Uri url, IWebSnapshotSize size) { Image result = null; using (var completed = new AutoResetEvent(false)) using (var browser = new WebBrowser()) { browser.ScrollBarsEnabled = false; browser.DocumentCompleted += delegate { result = ExtractSnapshot(browser, size); completed.Set(); }; browser.Navigate(url); //completed.WaitOne(); while (result == null) { Thread.Sleep(0); Application.DoEvents(); } } return result; } private static Image ExtractSnapshot(WebBrowser browser, IWebSnapshotSize size) { browser.ScrollBarsEnabled = false; var bounds = size.Resize(browser); var bitmap = new Bitmap(bounds.Width, bounds.Height); browser.BringToFront(); browser.DrawToBitmap(bitmap, bounds); return bitmap; } } }