public static unsafe void DirectBlit(BitmapSurface buffer, ref Texture2D texture2D) { //TODO : Test if d3dt can be cached var d3Dt = GetIUnknownObject <IDirect3DTexture9>(texture2D); //XE.Performance.Log("IDirect3DTexture9 Is "+(d3dt!=null ? d3dt.ToString():"null")); //D3DSURFACE_DESC desc=new D3DSURFACE_DESC(); //Marshal.ThrowExceptionForHR(d3dt.GetLevelDesc(0, out desc)); //XE.Performance.Log("LevelDesc Format "+desc.Format.ToString()); //XE.Performance.Log("LevelDesc MultiSampleQuality "+desc.MultiSampleQuality.ToString()); //XE.Performance.Log("LevelDesc MultiSampleType "+desc.MultiSampleType.ToString()); //XE.Performance.Log("LevelDesc Pool "+desc.Pool.ToString()); //XE.Performance.Log("LevelDesc Type "+desc.Type.ToString()); //XE.Performance.Log("LevelDesc Usage "+desc.Usage.ToString()); //XE.Performance.Log("LevelDesc Width "+desc.Width.ToString()); //XE.Performance.Log("LevelDesc Height "+desc.Height.ToString()); D3DlockedRect lockrect; var rect = new Rect(); Marshal.ThrowExceptionForHR(d3Dt.LockRect(0, out lockrect, rect, 0)); //XE.Performance.Log("LockRect Pitch "+lockrect.Pitch.ToString()); //XE.Performance.Log("LockRect pBits "+((uint)lockrect.pBits).ToString()); //buffer.CopyTo(destBuffer, destRowSpan, destDepth, convertoRGBA, flipY); buffer.CopyTo((IntPtr)(uint)(lockrect.pBits), lockrect.Pitch, 4, false, false); d3Dt.UnlockRect(0); //Meve onto Dispose() if d3dt will be cached d3dt Marshal.ReleaseComObject(d3Dt); }
private static void LoginAndTakeScreenShot(WebView wv) { dynamic document = (JSObject)wv.ExecuteJavascriptWithResult("document"); using (document) { //Works var tbox = document.getElementById("Email"); tbox.value = "*****@*****.**"; //Works var pbox = document.getElementById("Passwd"); pbox.value = "**********"; FrameEventHandler handler = null; handler = (sender, args) => { if (args.IsMainFrame) { wv.LoadingFrameComplete -= handler; BitmapSurface surface = (BitmapSurface)wv.Surface; surface.SaveToPNG("result.png", true); System.Diagnostics.Process.Start("result.png"); WebCore.Shutdown(); } }; wv.LoadingFrameComplete += handler; var sbox = document.getElementById("signIn"); sbox.click(); } }
private void TakeScreenShot(String Name = "Image") { //Thread.Sleep(3000); BitmapSurface surface = (BitmapSurface)wv.Surface; surface.SaveToPNG(String.Format("{0}_{1}.png", ++i, Name), true); Log(String.Format("ScreenShot Taken {0}", i)); }
private void PutColorAtPosition(Point pixel, Color color, BitmapSurface surface) { surface.SetColor( (int)pixel.X, (int)pixel.Y, color); surface.InvalidateVisual(); }
public Direct3D9Texture(string name, BitmapSurface surface, bool premultiplyAlpha) : base(name, surface) { if (premultiplyAlpha) { this.premultiplyAlpha(); } convertToDirect3D9Texture(true, false); }
public GlTexture(OpenGLRenderer renderer, string name, BitmapSurface surface, bool mipmapped, bool premultiplyAlpha) : base(name, surface) { _renderer = renderer; if (premultiplyAlpha) { this.premultiplyAlpha(); } convertToOpenGlTexture(true, false, mipmapped); }
public PixelEditorSurface() { drawingSurface = new BitmapSurface(this); gridLines = CreateGridLines(); previewSurface = new BitmapSurface(this); Cursor = Cursors.Pen; AddVisualChild(drawingSurface); AddVisualChild(previewSurface); AddVisualChild(gridLines); }
internal void webView_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "Surface") { if (surface != null) { surface.Dispose(); } surface = webView.Surface as BitmapSurface; initialized = true; } }
////////////////////////////////////////////////////////////////////////////////////////// // CONSTRUCTOR & DESTRUCTOR /// <summary> /// Main constructor. /// </summary> /// <param name="device">The d3d11 device on which to connect the texture.</param> /// <param name="context">The context to be used for this webtexture.</param> /// <param name="url">The url to use.</param> /// /// <param name="updateIfSurfaceIsNotDirty">Look at member!</param> /// <param name="width">The webview's width.</param> /// <param name="height">The webview's height.</param> /// <param name="isTransparent">Defines, whether the background of the site shall be transparent or not.</param> public WebTexture( Device device, DeviceContext context, Uri url, bool updateIfSurfaceIsNotDirty = true, int width = 1920, int height = 1080, bool isTransparent = true) : base(device) { UpdateIfSurfaceIsNotDirty = updateIfSurfaceIsNotDirty; // setup awesomium view WebSession webSession = WebCore.CreateWebSession(new WebPreferences { CustomCSS = "::-webkit-scrollbar { width: 0px; height: 0px; } ", }); _view = WebCore.CreateWebView(width, height, webSession); _view.Source = url; _view.IsTransparent = isTransparent; while (_view.IsLoading) { WebCore.Update(); } // init texture Context = context; Texture2DDescription description = new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.Write, Format = SlimDX.DXGI.Format.B8G8R8A8_UNorm, Height = _view.Height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Dynamic, Width = _view.Width }; _texture = new Texture2D(Device, description); _surface = _view.Surface as BitmapSurface; }
private void WebView_LoadingFrameComplete(object sender, FrameEventArgs e) { if (!e.IsMainFrame) { return; } BitmapSurface surface = (BitmapSurface)webView.Surface; surface.SaveToPNG("result.png", true); WebCore.Shutdown(); MessageBox.Show("end"); }
private int browserheight; // Height of browser. /// <summary> /// Instantiates a new tab. /// </summary> /// <param name="id"></param> /// <param name="URL"></param> /// <param name="w"></param> /// <param name="h"></param> /// <param name="x"></param> /// <param name="y"></param> public BrowserTab(int id, string URL, int w, int h, int x, int y) { ID = id; url = URL; browserwidth = w; browserheight = h; s = new BitmapSurface(w, h); webBytes = new byte[w * h * 4]; BrowserTex = new Texture((uint)browserwidth, (uint)browserheight); View = new Sprite(BrowserTex); View.Position = new Vector2f((uint)x, (uint)y); WebSession session = WebCore.CreateWebSession(new WebPreferences() { WebSecurity = false, FileAccessFromFileURL = true, UniversalAccessFromFileURL = true, LocalStorage = true, }); MyTab = WebCore.CreateWebView(browserwidth, browserheight, session, WebViewType.Offscreen); //MyTab.ShowJavascriptDialog += (sender, e) => //{ // Console.WriteLine(e.Message); // BrowserManager.DestroyTab(ID); // BrowserManager.NewTab(ID, url, w, h, x, y); //}; MyTab.Source = new Uri(URL); MyTab.Surface = s; s.Updated += (sender, e) => { unsafe { fixed(Byte *byteptr = webBytes) { s.CopyTo((IntPtr)byteptr, s.RowSpan, 4, true, false); BrowserTex.Update(webBytes); } } }; }
private int browserheight; // Height of browser. /// <summary> /// Instantiates a new tab. /// </summary> /// <param name="id"></param> /// <param name="URL"></param> /// <param name="w"></param> /// <param name="h"></param> /// <param name="x"></param> /// <param name="y"></param> public BrowserTab(int id, string URL, int w, int h, int x, int y) { ID = id; url = URL; browserwidth = w; browserheight = h; s = new BitmapSurface(w, h); webBytes = new byte[w * h * 4]; BrowserTex = new Texture((uint)browserwidth, (uint)browserheight); View = new Sprite(BrowserTex); View.Position = new Vector2f((uint)x, (uint)y); WebSession session = WebCore.CreateWebSession(new WebPreferences() { WebSecurity = false, FileAccessFromFileURL = true, UniversalAccessFromFileURL = true, LocalStorage = true, }); MyTab = WebCore.CreateWebView(browserwidth, browserheight, session, WebViewType.Offscreen); MyTab.IsTransparent = true; MyTab.Source = new Uri(URL); MyTab.Surface = s; MyTab.ShowJavascriptDialog += (sender, e) => { Console.WriteLine("JS: " + e.Message + " : " + id + " " + this.GetType().ToString()); Callback(e.Message); }; s.Updated += (sender, e) => { if (!Active) { return; } for (int i = 0; i < GlobalData.UISmooth; i++) { UpdateTexture(); } }; }
private void ColorPixelsOnSurface(List <ColoredPixel> pixels, BitmapSurface surface) { if (pixels != null) { foreach (var pixel in pixels) { if (pixel.Point != null && PointHelper.PointOnSurface(pixel.Point, PixelWidth, PixelHeight)) { surface.SetColor( (int)pixel.Point.X, (int)pixel.Point.Y, pixel.Color); } } } }
private Point GetMousePixel(BitmapSurface surface) { Point returnValue = new Point(-1, -1); var mousePosition = Mouse.GetPosition(surface); var foo = surface.DesiredSize; var surfaceWidth = PixelWidth * Magnification; var surfaceHeight = PixelHeight * Magnification; if (PointHelper.PointOnSurface(mousePosition, surfaceWidth, surfaceHeight)) { returnValue = new Point((int)(mousePosition.X / Magnification), (int)(mousePosition.Y / Magnification)); } return(returnValue); }
/// <summary> /// Updates texture. /// </summary> public void UpdateTexture() { BrowserManager.awesomiumContext.Send(state => { int sRow = s.RowSpan; BitmapSurface temp = s; unsafe { fixed(Byte * byteptr = webBytes) { temp.CopyTo((IntPtr)byteptr, sRow, 4, true, false); BrowserTex.Update(webBytes); } } }, null); }
public static void Main(string[] args) { using (var webView = WebCore.CreateWebView(800, 600)) { webView.Source = new Uri("http://www.google.com"); webView.LoadingFrameComplete += (s, e) => { if (!e.IsMainFrame) { return; } BitmapSurface surface = (BitmapSurface)webView.Surface; surface.SaveToPNG("result.png", true); WebCore.Shutdown(); }; } WebCore.Run(); }
// This is executed on Awesomium's thread. static void TakeSnapshots(WebView view, string filePath) { if (!view.IsLive) { // Dispose the view. view.Dispose(); return; } // A BitmapSurface is assigned by default to all WebViews. BitmapSurface surface = (BitmapSurface)view.Surface; // Save the buffer to a PNG image. surface.SaveToJPEG(filePath, 75); view.Dispose(); savingSnapshots--; return; }
public Direct3D9CubeMap(Device device, string name, BitmapSurface front, BitmapSurface back, BitmapSurface left, BitmapSurface right, BitmapSurface up, BitmapSurface down) : base(name) { _cubeMap = new CubeTexture(device, front.Width, 0, Usage.AutoGenerateMipMap, Format.X8R8G8B8, Pool.Managed); writeFacePixels(CubeMapFace.PositiveX, front.Pixels, front.Width, front.Height); writeFacePixels(CubeMapFace.NegativeX, back.Pixels, back.Width, back.Height); writeFacePixels(CubeMapFace.PositiveZ, right.Pixels, right.Width, right.Height); writeFacePixels(CubeMapFace.NegativeZ, left.Pixels, left.Width, left.Height); writeFacePixels(CubeMapFace.PositiveY, up.Pixels, up.Width, up.Height); if (down != null) { writeFacePixels(CubeMapFace.NegativeY, down.Pixels, down.Width, down.Height); } else { // apparently the "down" face isn't needed. we'll just reuse the top. writeFacePixels(CubeMapFace.NegativeY, up.Pixels, up.Width, up.Height); } }
public GlCubeMap(OpenGLRenderer renderer, string name, BitmapSurface front, BitmapSurface back, BitmapSurface left, BitmapSurface right, BitmapSurface up, BitmapSurface down) : base(name) { _renderer = renderer; GL.GetError(); GL.GenTextures(1, out _glTexture); GL.BindTexture(TextureTarget.TextureCubeMap, _glTexture); const PixelFormat format = PixelFormat.Rgba; GL.TexImage2D(TextureTarget.TextureCubeMapPositiveX, 0, PixelInternalFormat.Rgba, front.Width, front.Height, 0, format, PixelType.UnsignedByte, front.Pixels); GL.TexImage2D(TextureTarget.TextureCubeMapNegativeX, 0, PixelInternalFormat.Rgba, back.Width, back.Height, 0, format, PixelType.UnsignedByte, back.Pixels); GL.TexImage2D(TextureTarget.TextureCubeMapPositiveZ, 0, PixelInternalFormat.Rgba, right.Width, right.Height, 0, format, PixelType.UnsignedByte, right.Pixels); GL.TexImage2D(TextureTarget.TextureCubeMapNegativeZ, 0, PixelInternalFormat.Rgba, left.Width, left.Height, 0, format, PixelType.UnsignedByte, left.Pixels); GL.TexImage2D(TextureTarget.TextureCubeMapPositiveY, 0, PixelInternalFormat.Rgba, up.Width, up.Height, 0, format, PixelType.UnsignedByte, up.Pixels); if (down != null) { GL.TexImage2D(TextureTarget.TextureCubeMapNegativeY, 0, PixelInternalFormat.Rgba, down.Width, down.Height, 0, format, PixelType.UnsignedByte, down.Pixels); } else { // apparently the "down" face isn't needed. we'll just reuse the top. GL.TexImage2D(TextureTarget.TextureCubeMapNegativeY, 0, PixelInternalFormat.Rgba, up.Width, up.Height, 0, format, PixelType.UnsignedByte, up.Pixels); } GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMinFilter, (int)All.Linear); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMagFilter, (int)All.Linear); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); if (GL.GetError() != ErrorCode.NoError) { throw new InvalidOperationException(); } }
public BasicUserHUD(PlanetScreen game, Rectangle area) : base(game.Game) { _area = area; Screen = game; Screen.GamePlayer.PlayerToolbarIndexChanged += GamePlayerOnPlayerToolbarIndexChanged; _spriteBatch = new SpriteBatch(game.Game.GraphicsDevice); AwesomiumThread = new Thread(() => { WebCore.Started += (s, e) => { _awesomiumContext = SynchronizationContext.Current; AwesomiumReady.Set(); }; WebCore.Run(); }); AwesomiumThread.Start(); WebCore.Initialize(new WebConfig()); AwesomiumReady.WaitOne(); _awesomiumContext.Post(state => { WebView = WebCore.CreateWebView(_area.Width, _area.Height, WebViewType.Offscreen); WebView.IsTransparent = true; WebView.CreateSurface += (s, e) => { Surface = new BitmapSurface(_area.Width, _area.Height); e.Surface = Surface; }; }, null); //_jsObject = WebView.CreateGlobalJavascriptObject("game"); //_jsObject["test"] = "Hello World!"; }
public GUI(Size size, IViewModel viewModel, SynchronizationContext awesomiumContext, DataSource dataSource) { _viewModel = viewModel; Size = size; _data = new Byte[Size.Width * 4 * Size.Height]; awesomiumContext.Post(state => { webView = WebCore.CreateWebView(Size.Width, Size.Height, WebViewType.Offscreen); webView.LoadingFrameFailed += webView_LoadingFrameFailed; webView.DocumentReady += WebViewOnDocumentReady; webView.IsTransparent = true; webView.CreateSurface += (s, e) => { _surface = new BitmapSurface(Size.Width, Size.Height); e.Surface = _surface; }; webView.WebSession.AddDataSource("gui", dataSource); webView.Source = viewModel.CreateUri(); webView.FocusView(); }, null); }
public void runCommands() { switch (commandNumber) { case 1: { Console.WriteLine("Typing Username..."); webView.ExecuteJavascript("document.getElementById('input_3').value='Username'"); break; } case 2: { Console.WriteLine("Typing Password..."); webView.ExecuteJavascript("document.getElementById('input_4').value='Password'"); break; } case 3: { Console.WriteLine("Typing First Name..."); click(410, 150); typeKeys("John"); break; } case 4: { Console.WriteLine("Typing Last Name..."); click(410, 197); typeKeys("Doe"); break; } case 5: { Console.WriteLine("Selecting Gender as Male..."); webView.ExecuteJavascript("document.getElementById('input_7_0').checked=true"); break; } case 6: { Console.WriteLine("Selecting 'Search Engine' in combo box..."); webView.ExecuteJavascript("document.getElementById('input_8').value='Search Engine'"); break; } default: { //webView.Render().SaveToPNG("result.png", true); BitmapSurface surface = (BitmapSurface)webView.Surface; surface.SaveToPNG("result.png", true); System.Diagnostics.Process.Start("result.png"); Console.WriteLine("Done running all commands, shutting down webcore..."); WebCore.Shutdown(); running = false; break; } } commandNumber++; }
// This is executed on Awesomium's thread. static void TakeSnapshots(WebView view, int messageLine, bool exit = true) { if (!view.IsLive) { // Dispose the view. view.Dispose(); return; } // Get the hostname. If it's empty, it must be our JS Console that saves. string host = String.IsNullOrEmpty(view.Source.Host) ? "JS" : view.Source.Host; // A BitmapSurface is assigned by default to all WebViews. BitmapSurface surface = (BitmapSurface)view.Surface; // Build a name for the saved image. string imageFile = String.Format("{0}.{1:yyyyMMddHHmmss}.png", host, DateTime.Now); // Save the buffer to a PNG image. surface.SaveToPNG(imageFile, true); // Print message. ReplaceLine(String.Format("Saved: {0}", imageFile), messageLine + 2); // Check if we can execute JavaScript // against the DOM. if (!view.IsDocumentReady) { // Print message. ReplaceLine("DOM not available.", messageLine + 1); if (!exit) { return; } // Dispose the view. view.Dispose(); savingSnapshots--; return; } // We demonstrate resizing to full height. ReplaceLine("Attempting to resize to full height... ", messageLine + 1); // This JS call will normally return the full height // of the page loaded. int docHeight = (int)view.ExecuteJavascriptWithResult(PAGE_HEIGHT_FUNC); // ExecuteJavascriptWithResult is a synchronous call. Synchronous // calls may fail. We check for errors that may occur. Note that // if you often get a Error.TimedOut, you may need to set the // IWebView.SynchronousMessageTimeout property to a higher value // (the default is 800ms). Error lastError = view.GetLastError(); // Report errors. if (lastError != Error.None) { ReplaceLine(String.Format("Error: {0} occurred while getting the page's height.", lastError), messageLine + 1); } // Exit if the operation failed or the height is 0. if (docHeight == 0) { return; } // No more content to display. if (docHeight == view.Height) { // Print message. ReplaceLine("Full height already loaded.", messageLine + 1); if (!exit) { return; } // Dispose the view. view.Dispose(); savingSnapshots--; return; } // All predefined surfaces of Awesomium.NET, // support resizing. Here is a demonstration. surface.Resized += (s, e) => { // Print message. ReplaceLine("Surface Resized", messageLine + 1); // Build a name for the saved image. string fullImageFile = String.Format("{0}.{1:yyyyMMddHHmmss}.full.png", host, DateTime.Now); // Save the updated buffer to a new PNG image. surface.SaveToPNG(fullImageFile, true); // Print message. ReplaceLine(String.Format("Saved: {0}", fullImageFile), messageLine + 2); // Get Awesomium's synchronization context. You can only // acquire this from Awesomium's thread, but you can then // cache it or pass it to another thread to be used for // safe cross-thread calls to Awesomium. Here we just // demonstrate using Post to postpone the view's destruction // till the next update pass of the WebCore. SynchronizationContext syncCtx = SynchronizationContext.Current; // Check if a valid SynchronizationContext is available. if ((syncCtx != null) && (syncCtx.GetType() != typeof(SynchronizationContext))) { // Queue the destruction of the view. Code execution // will resume immediately (so we exit the event handler), // and the anonymous handler will be executed in the // next update pass. syncCtx.Post((v) => { WebView completedView = (WebView)v; if (!exit) { return; } // Dispose the view. completedView.Dispose(); savingSnapshots--; }, view); } }; // Call resize on the view. This will resize // and update the surface. view.Resize(view.Width, docHeight); }
public CubeMapResource CreateCubeMap(string name, BitmapSurface front, BitmapSurface back, BitmapSurface left, BitmapSurface right, BitmapSurface up, BitmapSurface down) { return(new Direct3D9CubeMap(_device, name, front, back, left, right, up, down)); }
public TextureResource CreateTexture(string name, BitmapSurface surface, bool mipmapped, bool premultiplyAlpha) { return(new Direct3D9Texture(name, surface, premultiplyAlpha)); }
public TextureResource CreateTexture(string name, BitmapSurface colorSurface, bool mipmapped) { return(new Direct3D9Texture(name, colorSurface)); }
static void Main(string[] args) { // Initialize the WebCore with default confiuration settings. WebCore.Initialize(new WebConfig() { LogPath = Environment.CurrentDirectory, LogLevel = LogLevel.Verbose }); // We demonstrate an easy way to hide the scrollbars by providing // custom CSS. Read more about how to style the scrollbars here: // http://www.webkit.org/blog/363/styling-scrollbars/. // Just consider that this setting is WebSession-wide. If you want to apply // a similar effect for single pages, you can use ExecuteJavascript // and pass: document.documentElement.style.overflow = 'hidden'; // (Unfortunately WebKit's scrollbar does not have a DOM equivalent yet) using (WebSession session = WebCore.CreateWebSession(new WebPreferences() { CustomCSS = "::-webkit-scrollbar { visibility: hidden; }" })) { // WebView implements IDisposable. Here we demonstrate // wrapping it in a using statement. using (WebView view = WebCore.CreateWebView(1280, 960, session)) { bool finishedLoading = false; Console.WriteLine("Loading: http://www.awesomium.com ..."); view.LoadURL(new Uri("http://www.awesomium.com")); view.LoadingFrameComplete += (s, e) => { Console.WriteLine(String.Format("Frame Loaded: {0}", e.FrameID)); // The main frame always finishes loading last for a given page load. if (e.IsMainFrame) { finishedLoading = true; } }; while (!finishedLoading) { Thread.Sleep(100); // A Console application does not have a synchronization // context, thus auto-update won't be enabled on WebCore. // We need to manually call Update here. WebCore.Update(); } // Print some more information. Console.WriteLine(String.Format("Page Title: {0}", view.Title)); Console.WriteLine(String.Format("Loaded URL: {0}", view.Source)); // A BitmapSurface is assigned by default to all WebViews. BitmapSurface surface = (BitmapSurface)view.Surface; // Save the buffer to a PNG image. surface.SaveToPNG("result.png", true); } // Destroy and dispose the view. } // Release and dispose the session. // Announce. Console.Write("Hit any key to see the result..."); Console.ReadKey(true); // Start the application associated with .png files // and display the file. Process.Start("result.png"); // Shut down Awesomium before exiting. WebCore.Shutdown(); }
public Direct3D9Texture(string name, BitmapSurface colorSurface) : base(name, colorSurface) { convertToDirect3D9Texture(true, true); }
static void Main(string[] args) { //AutomationSample main = new AutomationSample(); //main.update(); WebConfig config = WebConfig.Default; WebCore.Initialize(config); Uri url = new Uri("http://www.google.com"); WebPreferences prefs = WebPreferences.Default; //prefs.ProxyConfig = "198.1.99.26:3128"; //prefs.CustomCSS = "body { overflow:hidden; }"; //prefs.WebSecurity = false; //prefs.DefaultEncoding = "UTF-8"; using (WebSession session = WebCore.CreateWebSession(prefs)) { // WebView implements IDisposable. Here we demonstrate // wrapping it in a using statement. using (WebView webView = WebCore.CreateWebView(1366, 768, session, WebViewType.Offscreen)) { bool finishedLoading = false; bool finishedResizing = false; Console.WriteLine(String.Format("Loading: {0} ...", url)); // Load a URL. webView.Source = url; // This event is fired when a frame in the // page finished loading. webView.LoadingFrameComplete += (s, e) => { Console.WriteLine(String.Format("Frame Loaded: {0}", e.FrameId)); // The main frame usually finishes loading last for a given page load. if (e.IsMainFrame) { finishedLoading = true; } }; while (!finishedLoading) { Thread.Sleep(100); // A Console application does not have a synchronization // context, thus auto-update won't be enabled on WebCore. // We need to manually call Update here. WebCore.Update(); } // Print some more information. Console.WriteLine(String.Format("Page Title: {0}", webView.Title)); Console.WriteLine(String.Format("Loaded URL: {0}", webView.Source)); //webView.Render().SaveToPNG("result.png", true); //System.Diagnostics.Process.Start("result.png"); BitmapSurface surface = (BitmapSurface)webView.Surface; surface.SaveToPNG("result.png", true); System.Diagnostics.Process.Start("result.png"); } // Destroy and dispose the view. } // Release and dispose the session. // Shut down Awesomium before exiting. WebCore.Shutdown(); Console.WriteLine("Press any key to exit..."); Console.Read(); }
public static BitmapImage GetCaptchaData(this IWebView view) { int top; int left; int width; int height; JSObject obj = view.ExecuteJavascriptWithResult("document.querySelector('.gc-captcha-image').getBoundingClientRect()"); left = (int)obj["left"]; width = (int)obj["width"]; top = (int)obj["top"]; height = (int)obj["height"]; byte[] binaryData = new byte[] { }; BitmapSurface surface = view.Surface as BitmapSurface; BitmapSource bitmapSource = null; if (surface == null) { try { Awesomium.Windows.Controls.WebViewPresenter presenter = view.Surface as Awesomium.Windows.Controls.WebViewPresenter; bitmapSource = presenter.Image as BitmapSource; } catch (NullReferenceException ex) { } } if (bitmapSource != null) { using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new PngBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapSource)); enc.Save(outStream); Rectangle cropRect = new Rectangle(left, top, width, height); Bitmap src = Image.FromStream(outStream) as Bitmap; Bitmap target = new Bitmap(cropRect.Width, cropRect.Height); using (Graphics g = Graphics.FromImage(target)) { g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel); } //target.Save(@"captcha\yourfile.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); using (MemoryStream ms = new MemoryStream()) { target.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); binaryData = ms.ToArray(); } } } BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = new MemoryStream(binaryData); bitmap.EndInit(); return(bitmap); }
static void TakeSnapshots(WebView view) { // A BitmapSurface is assigned by default to all WebViews. BitmapSurface surface = (BitmapSurface)view.Surface; // Save the buffer to a PNG image. surface.SaveToPNG("result.png", true); // Show image. ShowImage("result.png"); // We demonstrate resizing to full height. Console.WriteLine("Attempting to resize to full height..."); // This JS call will normally return the full height // of the page loaded. int docHeight = (int)view.ExecuteJavascriptWithResult(PAGE_HEIGHT_FUNC); // ExecuteJavascriptWithResult is a synchronous call. Synchronous // calls may fail. We check for errors that may occur. Note that // if you often get a Error.TimedOut, you may need to set the // IWebView.SynchronousMessageTimeout property to a higher value // (the default is 800ms). Error lastError = view.GetLastError(); // Report errors. if (lastError != Error.None) { Console.WriteLine(String.Format("Error: {0} occurred while getting the page's height.", lastError)); } // Exit if the operation failed or the height is 0. if (docHeight == 0) { return; } // All predefined surfaces of Awesomium.NET, // support resizing. Here is a demonstration. surface.Resized += (s, e) => { Console.WriteLine("Surface Resized"); // Save the updated buffer to a new PNG image. surface.SaveToPNG("result2.png", true); // Show image. ShowImage("result2.png"); // Exit the update loop and shutdown the core. WebCore.Shutdown(); // Note that when Shutdown is called from // Awesomium's thread, anything after Shutdown // will not be executed since the thread exits // immediately. }; // Call resize on the view. This will resize // and update the surface. view.Resize(view.Width, docHeight); }