private static async void MainAsync(string cachePath, double zoomLevel)
            var browserSettings = new BrowserSettings();
            var requestContextSettings = new RequestContextSettings { CachePath = cachePath };
            // RequestContext can be shared between browser instances and allows for custom settings
            // e.g. CachePath
            using(var requestContext = new RequestContext(requestContextSettings))
            using (var browser = new ChromiumWebBrowser(TestUrl, browserSettings, requestContext))
                if (zoomLevel > 1)
                    browser.FrameLoadStart += (s, argsi) =>
                        var b = (ChromiumWebBrowser)s;
                        if (argsi.Frame.IsMain)
                            b.SetZoomLevel(zoomLevel);
                await LoadPageAsync(browser);
                // Wait for the screenshot to be taken.
                await browser.ScreenshotAsync().ContinueWith(DisplayBitmap);
                await LoadPageAsync(browser, "http://github.com");
                // Wait for the screenshot to be taken.
                await browser.ScreenshotAsync().ContinueWith(DisplayBitmap);
        }
        public BrowserForm()
            InitializeComponent();
            Load += BrowserFormLoad;
            Text = "CefSharp";
            WindowState = FormWindowState.Maximized;
            browser = new ChromiumWebBrowser(CefExample.DefaultUrl)
                Dock = DockStyle.Fill,
            toolStripContainer.ContentPanel.Controls.Add(browser);
            browser.DownloadHandler = new DownloadHandler();
            browser.MenuHandler = new MenuHandler();
            browser.NavStateChanged += OnBrowserNavStateChanged;
            browser.ConsoleMessage += OnBrowserConsoleMessage;
            browser.StatusMessage += OnBrowserStatusMessage;
            browser.TitleChanged += OnBrowserTitleChanged;
            browser.AddressChanged += OnBrowserAddressChanged;
            var version = String.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}", Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);
            DisplayOutput(version);
        }
示例#3
文件: Program.cs picibird/CefSharp
        public static void Main(string[] args)
            const string testUrl = "https://www.google.com/";
            Console.WriteLine("This example application will load {0}, take a screenshot, and save it to your desktop.", testUrl);
            Console.WriteLine("You may see a lot of Chromium debugging output, please wait...");
            Console.WriteLine();
            // You need to replace this with your own call to Cef.Initialize();
            CefExample.Init();
            // Create the offscreen Chromium browser.
            using (browser = new ChromiumWebBrowser(testUrl))
                // An event that is fired when the first page is finished loading.
                // This returns to us from another thread.
                if (captureFirstRenderedImage)
                    browser.ResourceHandler.RegisterHandler(testUrl, ResourceHandler.FromString("<html><body><h1>CefSharp OffScreen</h1></body></html>"));
                    browser.ScreenshotAsync().ContinueWith(DisplayBitmap);
                    browser.FrameLoadEnd += BrowserFrameLoadEnd;
                // We have to wait for something, otherwise the process will exit too soon.
                Console.ReadKey();
            // Clean up Chromium objects.  You need to call this in your application otherwise
            // you will get a crash when closing.
            Cef.Shutdown();
        }
 /// <summary>
 /// Asynchronously wait for the Chromium widget window to be created for the given ChromiumWebBrowser,
 /// and when created hook into its Windows message loop.
 /// </summary>
 /// <param name="browser">The browser to intercept Windows messages for.</param>
 /// <param name="forwardAction">This action will be called whenever a Windows message is received.</param>
 internal static void SetupLoop(ChromiumWebBrowser browser, Action<Message> forwardAction)
     Task.Factory.StartNew(() =>
             bool foundWidget = false;
             while (!foundWidget)
                 browser.Invoke((Action)(() =>
                     IntPtr chromeWidgetHostHandle;
                     if (ChromeWidgetHandleFinder.TryFindHandle(browser, out chromeWidgetHostHandle))
                         foundWidget = true;
                         new ChromeWidgetMessageInterceptor(browser, chromeWidgetHostHandle, forwardAction);
                         // Chrome hasn't yet set up its message-loop window.
                         Thread.Sleep(10);
         catch
             // Errors are likely to occur if browser is disposed, and no good way to check from another thread
 }
        public BrowserTabUserControl(string url)
            InitializeComponent();
            var browser = new ChromiumWebBrowser(url)
                Dock = DockStyle.Fill
            browserPanel.Controls.Add(browser);
            Browser = browser;
            browser.MenuHandler = new MenuHandler();
            browser.RequestHandler = new RequestHandler();
            browser.JsDialogHandler = new JsDialogHandler();
            browser.GeolocationHandler = new GeolocationHandler();
            browser.DownloadHandler = new DownloadHandler();
            //browser.FocusHandler = new FocusHandler(browser, urlTextBox);
            browser.NavStateChanged += OnBrowserNavStateChanged;
            browser.ConsoleMessage += OnBrowserConsoleMessage;
            browser.TitleChanged += OnBrowserTitleChanged;
            browser.AddressChanged += OnBrowserAddressChanged;
            browser.StatusMessage += OnBrowserStatusMessage;
            browser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;
            browser.IsLoadingChanged += OnIsLoadingChanged;
            browser.DragHandler = new DragHandler();
            browser.RegisterJsObject("bound", new BoundObject());
            CefExample.RegisterTestResources(browser);
            var version = String.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}", Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);
            DisplayOutput(version);
        }
示例#6
文件: BrowserTabUserControl.cs nick121212/xima_desktop3
        public BrowserTabUserControl(string url)
            InitializeComponent();
            var browser = new ChromiumWebBrowser(url)
                Dock = DockStyle.Fill
            browserPanel.Controls.Add(browser);
            Browser = browser;
            browser.MenuHandler = new MenuHandler();
            browser.NavStateChanged += OnBrowserNavStateChanged;
            browser.ConsoleMessage += OnBrowserConsoleMessage;
            browser.TitleChanged += OnBrowserTitleChanged;
            browser.AddressChanged += OnBrowserAddressChanged;
            browser.StatusMessage += OnBrowserStatusMessage;
            browser.HandleCreated += OnBrowserHandleCreated;
            var version = String.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}", Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);
            DisplayOutput(version);
            Disposed += BrowserTabUserControlDisposed;
        }
 public ParentFormMessageInterceptor(ChromiumWebBrowser browser)
     Browser = browser;
     // Get notified if our browser window parent changes:
     Browser.ParentChanged += ParentParentChanged;
     // Find the browser form to subclass to monitor WM_MOVE/WM_MOVING
     RefindParentForm();
 }
 public TabulationDemoForm()
     InitializeComponent();
     chromiumWebBrowser = new ChromiumWebBrowser(txtURL.Text) { Dock = DockStyle.Fill };
     var userControl = new UserControl { Dock = DockStyle.Fill };
     userControl.Controls.Add(chromiumWebBrowser);
     grpBrowser.Controls.Add(userControl);
 }
示例#9
显示文件
        private ChromeWidgetMessageInterceptor(ChromiumWebBrowser browser, IntPtr chromeWidgetHostHandle, Action<Message> forwardAction)
            AssignHandle(chromeWidgetHostHandle);
            this.browser = browser;
            browser.HandleDestroyed += BrowserHandleDestroyed;
            this.forwardAction = forwardAction;
        }
 public TabulationDemoForm()
     InitializeComponent();
     chromiumWebBrowser = new ChromiumWebBrowser(txtURL.Text) { Dock = DockStyle.Fill };
     var userControl = new UserControl { Dock = DockStyle.Fill };
     userControl.Enter += UserControlEnter;
     userControl.Leave += UserControlLeave;
     userControl.Controls.Add(chromiumWebBrowser);
     txtURL.GotFocus += TxtUrlGotFocus;
     txtURL.LostFocus += TxtUrlLostFocus;
     grpBrowser.Controls.Add(userControl);
 }
示例#11
文件: ChromiumFxControlWebBrowserWindow.cs sjoerd222888/MVVM.CEF.Glue
 public ChromiumFxControlWebBrowserWindow(ChromiumWebBrowser chromiumWebBrowser, IDispatcher dispatcher, IWebSessionLogger logger) 
     _Logger = logger;
     _dispatcher = dispatcher;
     _ChromiumWebBrowser = chromiumWebBrowser;
     _ChromiumWebBrowser.LoadHandler.OnLoadEnd += OnLoadEnd;
     _ChromiumWebBrowser.DisplayHandler.OnConsoleMessage += OnConsoleMessage;
     _ChromiumWebBrowser.OnV8ContextCreated += OnV8ContextCreated;
     _ChromiumWebBrowser.RemoteBrowserCreated += OnChromiumWebBrowser_RemoteBrowserCreated;
     _ChromiumWebBrowser.ContextMenuHandler.OnBeforeContextMenu += OnBeforeContextMenu;
     _ChromiumWebBrowser.RequestHandler.OnRenderProcessTerminated += RequestHandler_OnRenderProcessTerminated;
 }
        public BrowserTabUserControl(Action<string, int?> openNewTab, string url, bool multiThreadedMessageLoopEnabled)
            InitializeComponent();
            var browser = new ChromiumWebBrowser(url)
                Dock = DockStyle.Fill
            browserPanel.Controls.Add(browser);
            Browser = browser;
            browser.MenuHandler = new MenuHandler();
            browser.RequestHandler = new WinFormsRequestHandler(openNewTab);
            browser.JsDialogHandler = new JsDialogHandler();
            browser.GeolocationHandler = new GeolocationHandler();
            browser.DownloadHandler = new DownloadHandler();
            if (multiThreadedMessageLoopEnabled)
                browser.KeyboardHandler = new KeyboardHandler();
            browser.LifeSpanHandler = new LifeSpanHandler();
            browser.LoadingStateChanged += OnBrowserLoadingStateChanged;
            browser.ConsoleMessage += OnBrowserConsoleMessage;
            browser.TitleChanged += OnBrowserTitleChanged;
            browser.AddressChanged += OnBrowserAddressChanged;
            browser.StatusMessage += OnBrowserStatusMessage;
            browser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;
            browser.LoadError += OnLoadError;
            browser.RegisterJsObject("bound", new BoundObject());
            browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject());
            browser.RenderProcessMessageHandler = new RenderProcessMessageHandler();
            browser.DisplayHandler = new DisplayHandler();
            //browser.MouseDown += OnBrowserMouseClick;
            browser.HandleCreated += OnBrowserHandleCreated;
            //browser.ResourceHandlerFactory = new FlashResourceHandlerFactory();
            this.multiThreadedMessageLoopEnabled = multiThreadedMessageLoopEnabled;
            var eventObject = new ScriptedMethodsBoundObject();
            eventObject.EventArrived += OnJavascriptEventArrived;
            // Use the default of camelCaseJavascriptNames
            // .Net methods starting with a capitol will be translated to starting with a lower case letter when called from js
            browser.RegisterJsObject("boundEvent", eventObject, BindingOptions.DefaultBinder);
            CefExample.RegisterTestResources(browser);
            var version = String.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}", Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);
            DisplayOutput(version);
        }
示例#13
显示文件
 public ChromiumFxWpfWindow(IWebSessionLogger logger) 
     _Logger = logger;
     _ChromiumFxControl = new ChromiumFxControl()
         Visibility = Visibility.Hidden,
         VerticalAlignment = VerticalAlignment.Stretch,
         HorizontalAlignment = HorizontalAlignment.Stretch,
         ContextMenu = new ContextMenu() { Visibility = Visibility.Collapsed }
     _ChromiumWebBrowser = _ChromiumFxControl.ChromiumWebBrowser;
     var dispatcher = new WPFUIDispatcher(_ChromiumFxControl.Dispatcher);
     _chromiumFxControlWebBrowserWindow = new ChromiumFxControlWebBrowserWindow(_ChromiumWebBrowser, dispatcher, _Logger);
 }
        private static async void MainAsync(string cachePath, double zoomLevel)
            var browserSettings = new BrowserSettings();
            //Reduce rendering speed to one frame per second so it's easier to take screen shots
            browserSettings.WindowlessFrameRate = 1;
            var requestContextSettings = new RequestContextSettings { CachePath = cachePath };
            // RequestContext can be shared between browser instances and allows for custom settings
            // e.g. CachePath
            using(var requestContext = new RequestContext(requestContextSettings))
            using (var browser = new ChromiumWebBrowser(TestUrl, browserSettings, requestContext))
                if (zoomLevel > 1)
                    browser.FrameLoadStart += (s, argsi) =>
                        var b = (ChromiumWebBrowser)s;
                        if (argsi.Frame.IsMain)
                            b.SetZoomLevel(zoomLevel);
                await LoadPageAsync(browser);
                var preferences = requestContext.GetAllPreferences(true);
                // For Google.com pre-pupulate the search text box
                await browser.EvaluateScriptAsync("document.getElementById('lst-ib').value = 'CefSharp Was Here!'");
                // Wait for the screenshot to be taken,
                // if one exists ignore it, wait for a new one to make sure we have the most up to date
                await browser.ScreenshotAsync(true).ContinueWith(DisplayBitmap);
                await LoadPageAsync(browser, "http://github.com");
                //Gets a wrapper around the underlying CefBrowser instance
                var cefBrowser = browser.GetBrowser();
                // Gets a warpper around the CefBrowserHost instance
                // You can perform a lot of low level browser operations using this interface
                var cefHost = cefBrowser.GetHost();
                //You can call Invalidate to redraw/refresh the image
                cefHost.Invalidate(PaintElementType.View);
                // Wait for the screenshot to be taken.
                await browser.ScreenshotAsync(true).ContinueWith(DisplayBitmap);
        }
示例#15
0
        private void CreateBrowser()
            browser = new ChromiumWebBrowser("www.google.com")
                Dock = DockStyle.Fill,
            toolStripContainer.ContentPanel.Controls.Add(browser);
            browser.NavStateChanged += OnBrowserNavStateChanged;
            browser.ConsoleMessage += OnBrowserConsoleMessage;
            browser.StatusMessage += OnBrowserStatusMessage;
            browser.TitleChanged += OnBrowserTitleChanged;
            browser.AddressChanged += OnBrowserAddressChanged;
            browser.RegisterJsObject("bound", new BoundObject());
        }
        bool ILifeSpanHandler.OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
            //Default behaviour
            newBrowser = null;
            return false; //Return true to cancel the popup creation
            //EXPERIMENTAL: Demonstrates using a new instance of ChromiumWebBrowser to host the popup.
            var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
            ChromiumWebBrowser chromiumBrowser = null;
            var windowX = windowInfo.X;
            var windowY = windowInfo.Y;
            var windowWidth = (windowInfo.Width == int.MinValue) ? 600 : windowInfo.Width;
            var windowHeight = (windowInfo.Height == int.MinValue) ? 800 : windowInfo.Height;
            chromiumWebBrowser.Invoke(new Action(() =>
                var owner = chromiumWebBrowser.FindForm();
                chromiumBrowser = new ChromiumWebBrowser(targetUrl)
                    LifeSpanHandler = this
                chromiumBrowser.SetAsPopup();
                var popup = new Form
                    Left = windowX,
                    Top = windowY,
                    Width = windowWidth,
                    Height = windowHeight,
                    Text = targetFrameName
                owner.AddOwnedForm(popup);
                popup.Controls.Add(new Label { Text = "CefSharp Custom Popup" });
                popup.Controls.Add(chromiumBrowser);
                popup.Show();
            newBrowser = chromiumBrowser;
            return false;
        }
        bool ILifeSpanHandler.OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IWindowInfo windowInfo, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
            var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
            ChromiumWebBrowser chromiumBrowser = null;
            var windowX = (windowInfo.X == int.MinValue) ? double.NaN : windowInfo.X;
            var windowY = (windowInfo.Y == int.MinValue) ? double.NaN : windowInfo.Y;
            var windowWidth = (windowInfo.Width == int.MinValue) ? double.NaN : windowInfo.Width;
            var windowHeight = (windowInfo.Height == int.MinValue) ? double.NaN : windowInfo.Height;
            chromiumWebBrowser.Dispatcher.Invoke(() =>
                var owner = Window.GetWindow(chromiumWebBrowser);
                chromiumBrowser = new ChromiumWebBrowser
                    Address = targetUrl,
                var popup = new Window
                    Left = windowX,
                    Top = windowY,
                    Width = windowWidth,
                    Height = windowHeight,
                    Content = chromiumBrowser,
                    Owner = owner,
                    Title = targetFrameName
                popup.Closed += (o, e) =>
                    var w = o as Window;
                    if (w != null && w.Content is IWebBrowser)
                        (w.Content as IWebBrowser).Dispose();
                        w.Content = null;
                chromiumBrowser.LifeSpanHandler = this;
            newBrowser = chromiumBrowser;
            return false;
        }
示例#18
0
        private static async void MainAsync()
            // Create the offscreen Chromium browser.
            using (var browser = new ChromiumWebBrowser(TestUrl))
                await LoadPageAsync(browser);
                // Wait for the screenshot to be taken.
                await browser.ScreenshotAsync().ContinueWith(DisplayBitmap);
                await LoadPageAsync(browser, "http://github.com");
                // Wait for the screenshot to be taken.
                await browser.ScreenshotAsync().ContinueWith(DisplayBitmap);
        }
        private async void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
            if (browserContainer.Content is ChromiumWebBrowser)
                ChromiumWebBrowser oldBrowser = browserContainer.Content as ChromiumWebBrowser;
                browserContainer.Content = null;
                oldBrowser.Dispose();
            await Task.Delay(10);
            ChromiumWebBrowser browser = new ChromiumWebBrowser()
                Address = "http://www.google.com"
            browserContainer.Content = browser;
            //browser.ExecuteScriptAsync("document.body.innerHTML = '';");
        }
示例#20
		bool ILifeSpanHandler.OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IWindowInfo windowInfo, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
			var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
			ChromiumWebBrowser chromiumBrowser = null;
			var windowX = windowInfo.X;
			var windowY = windowInfo.Y;
			var windowWidth = (windowInfo.Width == int.MinValue) ? 600 : windowInfo.Width;
			var windowHeight = (windowInfo.Height == int.MinValue) ? 800 : windowInfo.Height;
			chromiumWebBrowser.Invoke(new Action(() =>
				var owner = chromiumWebBrowser.FindForm();
				chromiumBrowser = new ChromiumWebBrowser(targetUrl)
					LifeSpanHandler = this
				chromiumBrowser.SetAsPopup();
				var popup = new Form
					Left = windowX,
					Top = windowY,
					Width = windowWidth,
					Height = windowHeight,
					Text = targetFrameName
				owner.AddOwnedForm(popup);
				popup.Controls.Add(new Label { Text = "CefSharp Custom Popup" });
				popup.Controls.Add(chromiumBrowser);
				popup.Show();
			newBrowser = chromiumBrowser;
			return false;
		}
        public BrowserTabUserControl(string url)
            InitializeComponent();
            var browser = new ChromiumWebBrowser(url)
                Dock = DockStyle.Fill
            browserPanel.Controls.Add(browser);
            Browser = browser;
            browser.MenuHandler = new MenuHandler();
            browser.RequestHandler = new RequestHandler();
            browser.JsDialogHandler = new JsDialogHandler();
            browser.GeolocationHandler = new GeolocationHandler();
            browser.DownloadHandler = new DownloadHandler();
            browser.KeyboardHandler = new KeyboardHandler();
            //browser.LifeSpanHandler = new LifeSpanHandler();
            browser.LoadingStateChanged += OnBrowserLoadingStateChanged;
            browser.ConsoleMessage += OnBrowserConsoleMessage;
            browser.TitleChanged += OnBrowserTitleChanged;
            browser.AddressChanged += OnBrowserAddressChanged;
            browser.StatusMessage += OnBrowserStatusMessage;
            browser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;
            browser.LoadError += OnLoadError;
            browser.DragHandler = new DragHandler();
            if (CefSharpSettings.WcfEnabled)
                browser.RegisterJsObject("bound", new BoundObject());
            browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject());
            CefExample.RegisterTestResources(browser);
            var version = String.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}", Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);
            DisplayOutput(version);
        }
 /// <summary>
 /// Chrome's message-loop Window isn't created synchronously, so this may not find it.
 /// If so, you need to wait and try again later.
 /// </summary>
 public static bool TryFindHandle(ChromiumWebBrowser browser, out IntPtr chromeWidgetHostHandle)
     var browserHandle = browser.Handle;
     var windowHandleInfo = new ChromeWidgetHandleFinder(browserHandle);
     const string chromeWidgetHostClassName = "Chrome_RenderWidgetHostHWND";
     chromeWidgetHostHandle = windowHandleInfo.FindDescendantByClassName(chromeWidgetHostClassName);
     return chromeWidgetHostHandle != IntPtr.Zero;
 }
示例#24
0
 /// <summary>
 /// start up the embedded browser control
 /// </summary>
 private void InitializeBrowserControl()
     Cef.Initialize();
     Browser = new ChromiumWebBrowser(Url);
     this.Controls.Add(Browser);
 }
示例#25
显示文件
 public BrowserPage()
     InitializeComponent();
     // ChromiumWebBrowser.BrowserSettings.WebSecurity = CefSharp.CefState.Disabled;
     ChromiumWebBrowser.AddHandler(UIElement.MouseWheelEvent, new MouseWheelEventHandler(Page_MouseWheel), true);
 }
 public static void ExecuteFile(ChromiumWebBrowser browser, string file)
     ExecuteScript(browser, LoadResource(file), GetRootIdentifier(file));
 }
        public static void UpdatedBroswerMap(ChromiumWebBrowser chromiumWebBrowser, List <LocationCoordinate> locationCoordinates, int zoomLevelSiglePointView, MapProvider mapProvider)
            if (locationCoordinates.Count == 1)
                UpdateBrowserMap(chromiumWebBrowser, locationCoordinates[0], zoomLevelSiglePointView, mapProvider);
                LocationCoordinate locationCoordinateMax;
                LocationCoordinate locationCoordinateMin;
                LocationCoordinate locationCoordinateMap;
                CalulateLocationDistanceAndCenterPoints(locationCoordinates, out locationCoordinateMap, out locationCoordinateMin, out locationCoordinateMax);
                int zoomLevel = CalulateZoomLevel(locationCoordinateMin, locationCoordinateMax);
                switch (mapProvider)
                case MapProvider.OpenStreetMap:
                    string coordinates = "";
                    foreach (LocationCoordinate locationCoordinate in locationCoordinates)
                        if (coordinates != "")
                            coordinates += ", ";
                        coordinates +=
                            "[" +
                            (locationCoordinate.Longitude).ToString(CultureInfo.InvariantCulture) + ", " +
                            (locationCoordinate.Latitude).ToString(CultureInfo.InvariantCulture) +
                            ", 'Face']";
                    string locationMap = "";
                    locationMap = locationCoordinateMap.Longitude.ToString(CultureInfo.InvariantCulture) + ", " + locationCoordinateMap.Latitude.ToString(CultureInfo.InvariantCulture);
                    string htmlPage =
                        "<html>" + "\r\n" +
                        "<head>" + "\r\n" +
                        "  <title>Openlayers Marker Array Multilayer Example</title>" + "\r\n" +
                        "</head>" + "\r\n" +
                        "<body>" + "\r\n" +
                        "  <div id=\"mapdiv\"></div>" + "\r\n" +
                        "  <script src=\"http://www.openlayers.org/api/OpenLayers.js\"></script>" + "\r\n" +
                        "  <script>" + "\r\n" +
                        "    // Adapted from: harrywood.co.uk" + "\r\n" +
                        "    epsg4326 = new OpenLayers.Projection(\"EPSG:4326\")" + "\r\n" +
                        "    map = new OpenLayers.Map({" + "\r\n" +
                        "      div: \"mapdiv\"," + "\r\n" +
                        "      displayProjection: epsg4326   // With this setting, lat and lon are displayed correctly in MousePosition and permanent anchor" + "\r\n" +
                        "    });" + "\r\n" +
                        "    //   map = new OpenLayers.Map(\"mapdiv\");" + "\r\n" +
                        "    map.addLayer(new OpenLayers.Layer.OSM());" + "\r\n" +
                        "    map.addLayer(new OpenLayers.Layer.OSM(\"Wikimedia\"," + "\r\n" +
                        "      [\"https://maps.wikimedia.org/osm-intl/${z}/${x}/${y}.png\"]," + "\r\n" +
                        "      {" + "\r\n" +
                        "        attribution: \"&copy; <a href='http://www.openstreetmap.org/'>OpenStreetMap</a> and contributors, under an <a href='http://www.openstreetmap.org/copyright' title='ODbL'>open license</a>. <a href='https://www.mediawiki.org/wiki/Maps'>Wikimedia's new style (beta)</a>\"," + "\r\n" +
                        "        \"tileOptions\": { \"crossOriginKeyword\": null }" + "\r\n" +
                        "      })" + "\r\n" +
                        "   );" + "\r\n" +
                        "    // See https://wiki.openstreetmap.org/wiki/Tile_servers for other OSM-based layers" + "\r\n" +
                        "    map.addControls([" + "\r\n" +
                        "      new OpenLayers.Control.MousePosition()," + "\r\n" +
                        "      new OpenLayers.Control.ScaleLine()," + "\r\n" +
                        "      new OpenLayers.Control.LayerSwitcher()," + "\r\n" +
                        "      new OpenLayers.Control.Permalink({ anchor: true })" + "\r\n" +
                        "    ]);" + "\r\n" +
                        "    projectTo = map.getProjectionObject(); //The map projection (Spherical Mercator)" + "\r\n" +
                        "    var lonLat = new OpenLayers.LonLat(" + locationMap + ").transform(epsg4326, projectTo);" + "\r\n" +
                        "    var zoom = " + zoomLevel.ToString() + ";" + "\r\n" +
                        "    if (!map.getCenter()) {" + "\r\n" +
                        "      map.setCenter(lonLat, zoom);" + "\r\n" +
                        "    }" + "\r\n" +
                        "    // Put your point-definitions here" + "\r\n" +
                        "    var markers = [" + "\r\n" +
                        coordinates + "\r\n" +
                        "    ];" + "\r\n" +
                        "    var colorList = [\"red\", \"blue\", \"yellow\"];" + "\r\n" +
                        "    var layerName = [markers[0][2]];" + "\r\n" +
                        "    var styleArray = [new OpenLayers.StyleMap({ pointRadius: 6, fillColor: colorList[0], fillOpacity: 0.5 })];" + "\r\n" +
                        "    var vectorLayer = [new OpenLayers.Layer.Vector(layerName[0], { styleMap: styleArray[0] })];		// First element defines first Layer"+ "\r\n" +
                        "    var j = 0;" + "\r\n" +
                        "    for (var i = 1; i < markers.length; i++) {" + "\r\n" +
                        "      if (!layerName.includes(markers[i][2])) {" + "\r\n" +
                        "        j++;" + "\r\n" +
                        "        layerName.push(markers[i][2]);															// If new layer name found it is created"+ "\r\n" +
                        "        styleArray.push(new OpenLayers.StyleMap({ pointRadius: 6, fillColor: colorList[j % colorList.length], fillOpacity: 0.5 }));" + "\r\n" +
                        "        vectorLayer.push(new OpenLayers.Layer.Vector(layerName[j], { styleMap: styleArray[j] }));" + "\r\n" +
                        "      }" + "\r\n" +
                        "    }" + "\r\n" +
                        "    //Loop through the markers array" + "\r\n" +
                        "    for (var i = 0; i < markers.length; i++) {" + "\r\n" +
                        "      var lon = markers[i][0];" + "\r\n" +
                        "      var lat = markers[i][1];" + "\r\n" +
                        "      var feature = new OpenLayers.Feature.Vector(" + "\r\n" +
                        "        new OpenLayers.Geometry.Point(lon, lat).transform(epsg4326, projectTo)," + "\r\n" +
                        "        { description: \"marker number \" + i }" + "\r\n" +
                        "        // see http://dev.openlayers.org/docs/files/OpenLayers/Feature/Vector-js.html#OpenLayers.Feature.Vector.Constants for more options" + "\r\n" +
                        "      );" + "\r\n" +
                        "      vectorLayer[layerName.indexOf(markers[i][2])].addFeatures(feature);" + "\r\n" +
                        "    }" + "\r\n" +
                        "    for (var i = 0; i < layerName.length; i++) {" + "\r\n" +
                        "      map.addLayer(vectorLayer[i]);" + "\r\n" +
                        "    }" + "\r\n" +
                        "  </script>" + "\r\n" +
                        "</body>" + "\r\n" +
                        "</html>" + "\r\n";
                    //Create directory, filename and remove old arg file
                    string exiftoolArgFile = FileHandler.GetLocalApplicationDataPath("openstreetmap.html", true, null);
                    if (File.Exists(exiftoolArgFile))
                        FileHandler.Delete(exiftoolArgFile, false);
                    using (StreamWriter sw = new StreamWriter(exiftoolArgFile, false, Encoding.UTF8))
                        sw.WriteLine(htmlPage);
                    chromiumWebBrowser.Load(exiftoolArgFile);
                    break;
                case MapProvider.GoogleMap:
                    //https://www.google.com/maps/dir/33.93729,-106.85761/33.91629,-106.866761/33.98729,-106.85861//33.91629,-106.866761,11z/@33.9338371,-106.9191602,12z
                     * https://www.google.com/maps/dir
                     * /33.93729,-106.85761
                     * /33.91629,-106.866761
                     * /33.98729,-106.85861
                     * //33.91629,-106.866761,11z
                     * /@33.9338371,-106.9191602,12z
                     * https://www.google.com/maps/dir
                     * /59.97613,10.67896
                     * /59.97614,10.67897
                     * /59.97615,10.67898
                     * /59.976044,10.6788366
                     * /@59.9766696,10.676853,17z/data=!3m1!4b1!4m2!4m1!3e0
                     * https://www.google.com/maps/dir/59.97615,10.67896/59.97615,10.67896/59.97615,10.67896/59.976044,10.6788366/@59.9766696,10.676853,17z/data=!3m1!4b1!4m2!4m1!3e0
                    //LocationCoordinate locationCoordinateMap = CalulateSenterOfLocationPoints(locationCoordinates);
                    string googleUrl = "https://www.google.com/maps/dir";
                    foreach (LocationCoordinate locationCoordinate in locationCoordinates)
                        googleUrl +=
                            "/" + locationCoordinate.Latitude.ToString(CultureInfo.InvariantCulture) +
                            "," + locationCoordinate.Longitude.ToString(CultureInfo.InvariantCulture);
                    googleUrl +=
                        "/@" + locationCoordinateMap.Latitude.ToString(CultureInfo.InvariantCulture) +
                        "," + locationCoordinateMap.Longitude.ToString(CultureInfo.InvariantCulture) +
                        "," + ConvertZoomLevelToGoogle(zoomLevel).ToString() + "z";
                    chromiumWebBrowser.Load(googleUrl);
                    break;
        }
        public BrowserForm()
            InitializeComponent();
            LogWriteLine("CfxRuntime.ApiHash(0): " + CfxRuntime.ApiHash(0));
            LogWriteLine("CfxRuntime.ApiHash(1): " + CfxRuntime.ApiHash(1));
            LogWriteLine("CfxRuntime.GetCefVersion(): " + CfxRuntime.GetCefVersion());
            LogWriteLine("CfxRuntime.GetChromeVersion(): " + CfxRuntime.GetChromeVersion());
            LogWriteLine("Platform OS: {0}; Arch: {1}", CfxRuntime.PlatformOS, CfxRuntime.PlatformArch);
            LogWriteLine();
            ChromiumWebBrowser.RemoteProcessCreated += (e) => {
                LogWriteLine("Remote render process created with process id {0}", CfxRemoteCallContext.CurrentContext.ProcessId, CfxRemoteCallContext.CurrentContext.ThreadId);
                e.RenderProcessHandler.OnRenderThreadCreated += (s, e1) => {
                    LogWriteLine("RenderProcessHandler.OnRenderThreadCreated, process id = {0}", CfxRemoteCallContext.CurrentContext.ProcessId);
                e.RenderProcessHandler.OnBrowserDestroyed += (s, e1) => {
                    // this is never reached.
                    LogWriteLine("RenderProcessHandler.OnBrowserDestroyed, process id = {0}, browser id = {1}", CfxRemoteCallContext.CurrentContext.ProcessId, e1.Browser.Identifier);
                e.RenderProcessHandler.OnBrowserCreated += (s, e1) => {
                    LogWriteLine("RenderProcessHandler.OnBrowserCreated, process id = {0}, browser id = {1}", CfxRemoteCallContext.CurrentContext.ProcessId, e1.Browser.Identifier);
                e.RenderProcessHandler.OnFocusedNodeChanged += (s, e1) => {
                    LogWriteLine("RenderProcessHandler.OnFocusedNodeChanged, process id = {0}, browser id = {1}, node = {2}", CfxRemoteCallContext.CurrentContext.ProcessId, e1.Browser.Identifier, e1.Node?.Name);
            LoadUrlButton.Click += new EventHandler(LoadUrlButton_Click);
            UrlTextBox.KeyDown  += new KeyEventHandler(UrlTextBox_KeyDown);
            JSHelloWorldButton.Click += new EventHandler(JSHelloWorldButton_Click);
            JSTestPageButton.Click   += new EventHandler(TestButton_Click);
            VisitDomButton.Click     += new EventHandler(VisitDomButton_Click);
            WebBrowser.GlobalObject.AddFunction("CfxHelloWorld").Execute      += CfxHelloWorld_Execute;
            WebBrowser.GlobalObject.AddFunction("testDoubleCallback").Execute += TestDoubleCallback_Execute;
            // related to issue #65
            WebBrowser.GlobalObject.AddFunction("ArrayTestCallback").Execute += (s, e1) => {
                var array = e1.Arguments[0];
                var v0    = array.GetValue(0);
                var v1    = array.GetValue(1);
                if (v0 != null)
                    LogWriteLine("Array test function works: v0 = {0}, v1 = {1}", v0.IntValue, v1.IntValue);
                    LogWriteLine("Array test function: array is broken.");
            // related to pull request #1
            WebBrowser.GlobalObject.AddFunction("ListKeysInDocumentObject").Execute += (s, e1) => {
                var           doc  = e1.Arguments[0];
                List <string> keys = new List <string>();
                if (doc.GetKeys(keys))
                    LogWriteLine("document has {0} keys:", keys.Count);
                    keys.ForEach(k => LogWriteLine(k));
                    LogWriteLine("GetKeys returned false.");
            WebBrowser.GlobalObject.Add("TestObject", new JsTestObject(this));
            var sleepFunction = new JSFunction(JSInvokeMode.DontInvoke);
            sleepFunction.Execute += (s, e) => {
                LogWriteLine("Sleep function: sleep 5 seconds...");
                Thread.Sleep(5000);
                try {
                    var x = e.Arguments[0].IntValue;
                    LogWriteLine("Sleep function: Event args accessed sucessfully.");
                } catch (Exception ex) {
                    LogWriteLine("Sleep function: Error accessing event args:");
                    LogWriteLine(ex.ToString());
            WebBrowser.GlobalObject.Add("SleepFunction", sleepFunction);
            var html = @"
                <head><script>
                    function testlog(text) {
                        document.getElementById('testfunc_result').innerHTML += '<br>' + text;
                </script>
                <script>
                    function doubleCallback(arg1, arg2) {
                        testlog('Function doubleCallback() called. Arguments:');
                        testlog(arg1);
                        testlog(arg2);
                        return 'This text is returned from doubleCallback()';
                    function clearTestLog() {
                        document.getElementById('testfunc_result').innerHTML = '';
                </script>
                </head>
                    <br><br><b>Local resource/javascript integration test page.</b>
                    <hr><br><br>
                    Local resource image:<br>
                    <img src='http://localresource/image'><br><br>
                    <a href='http://www.google.com/' onclick=""window.open('http://www.google.com/', 'Popup test', 'width=800,height=600,scrollbars=yes'); return false;"">open popup window.open</a>
                    <a href='http://www.google.com/' target=blank>open popup target=blank</a>
                    <br><br>
                    <button id='testbutton1' onclick=""document.getElementById('testfunc_result').innerHTML += '<br>' + CfxHelloWorld('this is the hello world function');"">Execute CfxHelloWorld()</button>
                    <button id='testbutton2' onclick=""
                        testlog('TestObject = ' + TestObject);
                        testlog('TestObject.testFunction = ' + TestObject.testFunction);
                        TestObject.testFunction('this is the test function');
                    "">Execute TestObject.testFunction()</button>
                    <button id='testbutton3' onclick=""
                        testlog('TestObject = ' + TestObject);
                        testlog('TestObject.anotherObject = ' + TestObject.anotherObject);
                        testlog('TestObject.anotherObject.anotherTestFunction = ' + TestObject.anotherObject.anotherTestFunction);
                        testlog(TestObject.anotherObject.anotherTestFunction('this is the other test function'));
                    "">Execute TestObject.anotherObject.anotherTestFunction()</button>
                    <button id='testbutton4' onclick=""
                        testlog('TestObject.dynamicProperty = ' + TestObject.dynamicProperty);
                        testlog('(define TestObject.dynamicProperty += 100)');
                        TestObject.dynamicProperty += 100;
                        testlog('TestObject.dynamicProperty = ' + TestObject.dynamicProperty);
                    "">Defined TestObject properties</button>
                    <button id='testbutton5' onclick=""
                        testlog('TestObject.foo = ' + TestObject.foo);
                        testlog('(define TestObject.foo = 100)');
                        TestObject.foo = 100;
                        testlog('TestObject.foo = ' + TestObject.foo);
                    "">Undefined TestObject properties</button>
                    <button id='testbutton6' onclick=""
                        testlog('Call native function testDoubleCallback(doubleCallback). Return value:');
                        testlog('Return value: ' + testDoubleCallback(doubleCallback));
                    "">Double Callback</button>
                    <br><br><div id='testfunc_result'></div>
            WebBrowser.SetWebResource("http://localresource/text.html", new Chromium.WebBrowser.WebResource(html));
            var bm = new System.Drawing.Bitmap(100, 100);
            using (var g = System.Drawing.Graphics.FromImage(bm)) {
                g.FillRectangle(System.Drawing.Brushes.Yellow, 0, 0, 99, 99);
                g.DrawRectangle(System.Drawing.Pens.Black, 0, 0, 99, 99);
                g.DrawLine(System.Drawing.Pens.Black, 0, 0, 99, 99);
            WebBrowser.SetWebResource("http://localresource/image", new Chromium.WebBrowser.WebResource(bm));
            WebBrowser.DisplayHandler.OnConsoleMessage += (s, e) => LogCallback(s, e);
            WebBrowser.DisplayHandler.OnTitleChange    += (s, e) => LogCallback(s, e);
            WebBrowser.DisplayHandler.OnStatusMessage  += (s, e) => LogCallback(s, e);
            WebBrowser.DisplayHandler.OnTitleChange += (s, e) => {
                var wb = ChromiumWebBrowser.FromCfxBrowser(e.Browser);
                LogWriteLine("ChromiumWebBrowser.FromCfxBrowser(e.Browser) == WebBrowser: {0}", wb == WebBrowser);
                var title = e.Title;
                BeginInvoke((MethodInvoker)(() => Text = "ChromiumWebBrowser - " + title));
            WebBrowser.LifeSpanHandler.OnBeforePopup += (s, e) => {
                LogCallback(s, e);
            WebBrowser.LoadHandler.OnLoadingStateChange += (s, e) => {
                if (e.IsLoading)
                    return;
                BeginInvoke((MethodInvoker)(() => {
                    UrlTextBox.Text = WebBrowser.Url.ToString();
            WebBrowser.LoadUrl("http://localresource/text.html");
            WebBrowser.FindToolbar.Visible = true;
            WebBrowser.OnV8ContextCreated += (s, e) => {
                if (e.Frame.IsMain)
                    CfrV8Value     retval;
                    CfrV8Exception exception;
                    if (e.Context.Eval("CfxHelloWorld()", null, 0, out retval, out exception))
                        LogWriteLine("OnV8ContextCreated: Eval succeeded, retval is '{0}'", retval.StringValue);
                        LogWriteLine("OnV8ContextCreated: Eval failed, exception is '{0}'", exception.Message);
            WebBrowser.GlobalObject.AddFunction("SubmitAsyncTestFunction").Execute += JS_SubmitAsyncTestFunction;
            WebBrowser.GlobalObject.AddFunction("bigStringFunction").Execute       += JS_bigStringFunction;
        }
        public MainForm()
            InitializeComponent();
            //this.FormBorderStyle = FormBorderStyle.FixedToolWindow; //FixedToolWindow;// 或SizableToolWindow
                string pageUrl = Utils.GetAppConfig("url");
                if (pageUrl.Trim().Length < 1)
                    pageUrl = "http://order.ampm365.cn/";
                if (typeof(ChromiumWebBrowser).Name == "ChromiumWebBrowser")
                    webCom      = new ChromiumWebBrowser(pageUrl);
                    webCom.Dock = DockStyle.Fill;
                    this.Controls.Add(webCom);
                    //加载页面
                    webCom.Load(pageUrl);
                    //Settings settings = new Settings();
                    //CEF.Initialize(settings);
                    //BrowserSettings settings2 = new BrowserSettings();
                    ////初始化webview
                    //webCom = new WebView(pageUrl, settings2);
                    //webCom.Dock = DockStyle.Fill;
                    ////加入到父控件
                    //webCom.Parent = this;
                    LogTools.SetConfig(Environment.CurrentDirectory + "\\", "PosPrint.log");
                    LogTools.Info("日志初始化成功...");
                catch (Exception ex)
                    MessageBox.Show("日志初始化失败:" + ex.Message);
                //注册打印服务
                regSvr();
                OpenCashBox_QS ocb = new OpenCashBox_QS();
                if (ocb.IsNec == 2)
                    bool isExists = Utils.IsExistsProcess(Utils.GetAppConfig("uanPosExeFullPath"));
                    if (!isExists)
                        MessageBox.Show("请先启动Pos主程序,然后再启动接单平台!如果已启动Pos主程序,那么请查看config文件,是否配置正确");
                        this.Dispose(true);
                Print print = new Print(ocb.IsNec);
                webCom.RegisterJsObject("Print", print);
                webCom.RegisterJsObject("OpenCashBox_QS", ocb);
                //webCom.RegisterJsObject("CallNotifyIcon", new CallNotifyIcon(this));
                //try
                //    print.CreateEANCode("1234567890123");
                //catch (Exception ex)
                //    LogTools.Info("测试生成条形码异常:" + ex.ToString());
                //#region test
                //string sssss = Utils.GetAppConfig("bmpUrl");
                ////string sssss = "http://bto.oh.quanshishequ.com/order/print/receiptPrint?orderId=54232356057";
                //print.print2Bitmap(sssss);
                //#endregion
            catch (Exception ex)
                MessageBox.Show(ex.Message);
        }
示例#31
0
        protected override void OnViewLoaded(object view)
            currentView = ((DynamicBrowserGrView)view);
            _internetAccessBrowser = new ChromiumWebBrowser()
                Address = this.HomeUrl
            _internetAccessBrowser.BrowserSettings = new CefSharp.BrowserSettings()
                OffScreenTransparentBackground = false,
            _internetAccessBrowser.Load(this.HomeUrl);
            _internetAccessBrowser.BrowserSettings.FileAccessFromFileUrls      = CefState.Enabled;
            _internetAccessBrowser.BrowserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
            _internetAccessBrowser.BrowserSettings.WebSecurity = CefState.Enabled;
            _internetAccessBrowser.BrowserSettings.Javascript  = CefState.Enabled;
            _internetAccessBrowser.RequestContext  = new RequestContext();
            _internetAccessBrowser.LifeSpanHandler = new LifeSpanHandler();
            _internetAccessBrowser.RequestHandler = new CustomRequestHandler("", log, sender, this.numberOfAvailablePagesToPrint, events);
            _internetAccessBrowser.DialogHandler  = new CustomDialogHandler();
            _internetAccessBrowser.MenuHandler    = new CustomMenuHandler();
            var boundGrObject = new CustomBoundObjectEl(this.numberOfAvailablePagesToPrint, this.log, sender, events);
            _internetAccessBrowser.RegisterJsObject("bound", boundGrObject);
            _internetAccessBrowser.FrameLoadEnd += boundGrObject.OnFrameLoadEnd;
            PopulatePanel(currentView);
            ((DynamicBrowserGrView)view).DynamicBrowser.Children.Add(_internetAccessBrowser);
            _internetAccessBrowser.MouseDown += _internetAccessBrowser_MouseDown;
            _internetAccessBrowser.TouchDown += _internetAccessBrowser_TouchDown;
            _internetAccessBrowser.TouchMove += _internetAccessBrowser_TouchMove;
            _internetAccessBrowser.PreviewMouseUp += _internetAccessBrowser_PreviewMouseUp;
            _internetAccessBrowser.Focus();
            this.RemainingTime = "30";
            // this.OpenKeyboard = true;
            this.TimeElapsed = 30;
            timer            = new DispatcherTimer();
            timer.Interval   = new TimeSpan(0, 1, 0);
            timer.Tick      += TimerTick;
            timer.Start();
            startTime     = DateTime.Now;
            UnitStartTime = DateTime.Now;
            base.OnViewLoaded(view);
        }
示例#32
0
        public async Task <string> AuthenticateAsync(string username, string password, string region, int otp)
            Region = region;
            string otpString = otp.ToString("D6");
            var browserSettings = new BrowserSettings()
                WindowlessFrameRate       = 1,
                ImageLoading              = CefState.Disabled,
                JavascriptAccessClipboard = CefState.Disabled,
                JavascriptCloseWindows    = CefState.Disabled,
                JavascriptDomPaste        = CefState.Disabled
            using (var browser = new ChromiumWebBrowser(LauncherReturnUrl, browserSettings))
                browser.RequestHandler = new CustomRequestHandler();
                string errorMsg = null;
                await LoadPageAsync(browser);
                var loginScript = $@"
                            document.querySelector('#_email').value = '{username}';
                            document.querySelector('#_password').value = '{password}';
                            document.querySelector('#btnLogin').click();";
                await browser.EvaluateScriptAsync(loginScript);
                errorMsg = await CheckErrorMsg();
                if (!string.IsNullOrEmpty(errorMsg))
                    return(errorMsg);
                var otpScript = $@"
                        document.querySelector('#otpInput1').value = '{otpString[0]}';
                        document.querySelector('#otpInput2').value = '{otpString[1]}';
                        document.querySelector('#otpInput3').value = '{otpString[2]}';
                        document.querySelector('#otpInput4').value = '{otpString[3]}'; 
                        document.querySelector('#otpInput5').value = '{otpString[4]}';
                        document.querySelector('#otpInput6').value = '{otpString[5]}';
                        document.querySelector('.btn.btn_big.btn_blue.btnCheckOtp').click();";
                await browser.EvaluateScriptAsync(otpScript);
                errorMsg = await CheckErrorMsg();
                if (!string.IsNullOrEmpty(errorMsg))
                    return(errorMsg);
                await LoadPageAsync(browser, AuthenticationEndPoint);
                var responseJObject = JsonConvert.DeserializeObject <JObject>(CustomResourceRequestHandler.ResponseData);
                if (responseJObject["_result"]["resultMsg"] == null)
                    throw new AuthenticationException("Failed to get PlayToken");
                var resultMsg = responseJObject["_result"]["resultMsg"].Value <string>();
                Cef.Shutdown();
                return(resultMsg);
        }
示例#33
文件: TvWinViewModel.cs huangke1993/JiangSu
 private void InitBrowser(ChromiumWebBrowser browser)
     _browser            = browser;
     _browser.LoadError += _browser_LoadError;
 }
 private void ExcuteLoadCommand(ChromiumWebBrowser browser)
     InitBrowser(browser);
     ShowHtmlPage();
 }
        public async Task CanSetUserAgentOverride()
            using (var browser = new ChromiumWebBrowser("www.google.com"))
                await browser.WaitForInitialLoadAsync();
                using (var devToolsClient = browser.GetDevToolsClient())
                    var brandsList = new List <UserAgentBrandVersion>();
                    var uab        = new UserAgentBrandVersion
                        Brand   = "Google Chrome",
                        Version = "89"
                    brandsList.Add(uab);
                    var uab2 = new UserAgentBrandVersion
                        Brand   = "Chromium",
                        Version = "89"
                    brandsList.Add(uab2);
                    var ua = new UserAgentMetadata
                        Brands          = brandsList,
                        Architecture    = "arm",
                        Model           = "Nexus 7",
                        Platform        = "Android",
                        PlatformVersion = "6.0.1",
                        FullVersion     = "89.0.4389.114",
                        Mobile          = true
                    await devToolsClient.Emulation.SetUserAgentOverrideAsync("Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/5(KHTML,likeGeckoChrome/89.0.4389.114Safari/537.36", null, null, ua);
                var userAgent = await browser.EvaluateScriptAsync("navigator.userAgent");
                Assert.True(userAgent.Success);
                Assert.Contains("Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/5(KHTML,likeGeckoChrome/89.0.4389.114Safari/537.36", Assert.IsType <string>(userAgent.Result));
                var brands = await browser.EvaluateScriptAsync("navigator.userAgentData.brands");
                Assert.True(brands.Success);
                dynamic brandsResult = brands.Result;
                Assert.Collection((IEnumerable <dynamic>)brandsResult,
                                  (dynamic d) =>
                    Assert.Equal("Google Chrome", d.brand);
                    Assert.Equal("89", d.version);
                                  (dynamic d) =>
                    Assert.Equal("Chromium", d.brand);
                    Assert.Equal("89", d.version);
                var highEntropyValues = await browser.EvaluateScriptAsPromiseAsync("return navigator.userAgentData.getHighEntropyValues(['architecture','model','platform','platformVersion','uaFullVersion'])");
                Assert.True(highEntropyValues.Success);
                dynamic highEntropyValuesResult = highEntropyValues.Result;
                Assert.Equal("arm", highEntropyValuesResult.architecture);
                Assert.Equal("Nexus 7", highEntropyValuesResult.model);
                Assert.Equal("Android", highEntropyValuesResult.platform);
                Assert.Equal("6.0.1", highEntropyValuesResult.platformVersion);
                Assert.Equal("89.0.4389.114", highEntropyValuesResult.uaFullVersion);
        }
文件: FocusHandler.cs numbersint/CefSharp
 public FocusHandler(ChromiumWebBrowser browser, ToolStripTextBox urlTextBox)
     this.browser = browser;
     this.urlTextBox = urlTextBox;
 }
示例#39
0
显示文件
        public void Init()
            InitializeComponent();
            IsManipulationEnabled = true;
            // ReSharper disable once UseObjectOrCollectionInitializer
            _host = new WindowsFormsHost();
            _host.IsManipulationEnabled = true;
            Loaded += CefView_Loaded;
            var settings = new CefSettings {
                RemoteDebuggingPort = RemoteDebuggingPort,
                CachePath           = CachePath,
                UserAgent           = UserAgent
            CefSharpSettings.ShutdownOnExit = false;
            switch (LogLevel)
            case 0:
                settings.LogSeverity = LogSeverity.Default;
                break;
            case 1:
                settings.LogSeverity = LogSeverity.Verbose;
                break;
            case 2:
                settings.LogSeverity = LogSeverity.Info;
                break;
            case 3:
                settings.LogSeverity = LogSeverity.Warning;
                break;
            case 4:
                settings.LogSeverity = LogSeverity.Error;
                break;
            case 99:
                settings.LogSeverity = LogSeverity.Disable;
                break;
            default:
                settings.LogSeverity = LogSeverity.Disable;
                break;
            settings.WindowlessRenderingEnabled = false;
            settings.BrowserSubprocessPath      = BrowserSubprocessPath;
            foreach (var kvp in CommandLineArgs)
                settings.CefCommandLineArgs.Add(kvp.Key, kvp.Value);
            Cef.EnableHighDPISupport();
            // ReSharper disable once InvertIf
            if (Cef.Initialize(settings))
                Browser = new ChromiumWebBrowser(InitialUrl)
                    Dock = DockStyle.Fill
                Browser.RegisterAsyncJsObject("webViewANE", new BoundObject(), BindingOptions.DefaultBinder);
                // ReSharper disable once UseObjectOrCollectionInitializer
                var dh = new DownloadHandler();
                dh.OnDownloadUpdatedFired += OnDownloadUpdatedFired;
                dh.OnBeforeDownloadFired  += OnDownloadFired;
                // ReSharper disable once UseObjectOrCollectionInitializer
                var kh = new KeyboardHandler();
                kh.OnKeyEventFired += OnKeyEventFired;
                if (EnableDownloads)
                    Browser.DownloadHandler = dh;
                Browser.KeyboardHandler = kh;
                // ReSharper disable once UseObjectOrCollectionInitializer
                var gh = new GeolocationHandler();
                gh.OnPermissionResult     += OnPermissionResult;
                Browser.GeolocationHandler = gh;
                // ReSharper disable once UseObjectOrCollectionInitializer
                var sh = new LifeSpanHandler(PopupBehaviour, PopupDimensions);
                sh.OnPermissionPopup += OnPermissionPopup;
                Browser.LifeSpanHandler              = sh;
                Browser.FrameLoadEnd                += OnFrameLoaded;
                Browser.AddressChanged              += OnBrowserAddressChanged;
                Browser.TitleChanged                += OnBrowserTitleChanged;
                Browser.LoadingStateChanged         += OnBrowserLoadingStateChanged;
                Browser.LoadError                   += OnLoadError;
                Browser.IsBrowserInitializedChanged += OnBrowserInitialized;
                Browser.StatusMessage               += OnStatusMessage;
                var rh = new RequestHandler(WhiteList);
                rh.OnUrlBlockedFired += OnUrlBlockedFired;
                Browser.RequestHandler = rh;
                _host.Child = Browser;
                MainGrid.Children.Add(_host);
        }
示例#40
0
显示文件
 public AppearanceJavaScriptsExecuter(ChromiumWebBrowser webBrowser)
     chromiumWebBrowser = webBrowser;
 }
示例#41
0
显示文件
 public CefCustomObject(ChromiumWebBrowser originalBrowser, BaiduAuto mainForm)
     _instanceBrowser  = originalBrowser;
     _instanceMainForm = mainForm;
 }
示例#42
0
文件: WinFormsPlatformAdapter.cs yu-kopylov/html-csharp-desktop-ui
        public void NavigateTo(WindowHandle window, string url)
            ChromiumWebBrowser browser = (ChromiumWebBrowser)window.NativeBrowser;
            browser.Load(url);
        }
示例#43
0
显示文件
        public async Task CanRegisterMultipleEventHandlers()
            using (var browser = new ChromiumWebBrowser("about:blank", automaticallyCreateBrowser: false))
                await browser.CreateBrowserAsync();
                using (var devToolsClient = browser.GetDevToolsClient())
                    DevToolsEventArgs devToolsEventArgs = null;
                    EventHandler <DevToolsEventArgs> devToolsEventHandler = (sender, args) =>
                        if (devToolsEventArgs == null)
                            devToolsEventArgs = args;
                    devToolsClient.DevToolsEvent += devToolsEventHandler;
                    RequestWillBeSentEventArgs requestWillBeSentEventArgs1 = null;
                    EventHandler <RequestWillBeSentEventArgs> requestWillBeSentEventHandler1 = (sender, args) =>
                        if (requestWillBeSentEventArgs1 == null)
                            requestWillBeSentEventArgs1 = args;
                    devToolsClient.Network.RequestWillBeSent += requestWillBeSentEventHandler1;
                    RequestWillBeSentEventArgs requestWillBeSentEventArgs2 = null;
                    EventHandler <RequestWillBeSentEventArgs> requestWillBeSentEventHandler2 = (sender, args) =>
                        if (requestWillBeSentEventArgs2 == null)
                            requestWillBeSentEventArgs2 = args;
                    devToolsClient.Network.RequestWillBeSent += requestWillBeSentEventHandler2;
                    // enable events
                    await devToolsClient.Network.EnableAsync();
                    await browser.LoadUrlAsync("www.google.com");
                    Assert.NotNull(devToolsEventArgs);
                    Assert.NotNull(requestWillBeSentEventArgs1);
                    Assert.NotNull(requestWillBeSentEventArgs2);
                    Assert.Equal(requestWillBeSentEventArgs1.RequestId, requestWillBeSentEventArgs2.RequestId);
                    // remove second event handler
                    devToolsClient.Network.RequestWillBeSent -= requestWillBeSentEventHandler2;
                    devToolsEventArgs           = null;
                    requestWillBeSentEventArgs1 = null;
                    requestWillBeSentEventArgs2 = null;
                    await browser.LoadUrlAsync("www.google.com");
                    Assert.NotNull(devToolsEventArgs);
                    Assert.NotNull(requestWillBeSentEventArgs1);
                    Assert.Null(requestWillBeSentEventArgs2);
        }
示例#44
0
显示文件
文件: WinFormsPlatformAdapter.cs yu-kopylov/html-csharp-desktop-ui
        public void ReloadPage(WindowHandle window)
            ChromiumWebBrowser browser = (ChromiumWebBrowser)window.NativeBrowser;
            browser.Reload(true);
        }
示例#45
0
显示文件
示例#46
显示文件
文件: WinFormsPlatformAdapter.cs yu-kopylov/html-csharp-desktop-ui
        public void ShowDevTools(WindowHandle window)
            ChromiumWebBrowser browser = (ChromiumWebBrowser)window.NativeBrowser;
            browser.ShowDevTools();
        }
0
 public void InitBrowser()
     browser = new ChromiumWebBrowser("www.baidu.com");
     this.Controls.Add(browser);
     browser.Dock = DockStyle.Fill;
 }
示例#49
显示文件
 public LoginJsObject(ChromiumWebBrowser originalBrowser, UI.Main mainForm)
     _instanceBrowser  = originalBrowser;
     _instanceMainForm = mainForm;
 }
示例#50
显示文件
        /// <summary>
        /// The set custom handlers.
        /// </summary>
        /// <param name="browser">
        /// The browser.
        /// </param>
        public static void SetCustomHandlers(this ChromiumWebBrowser browser)
                foreach (var enumKey in CefCustomHandlerFakeTypes.GetAllCustomHandlerKeys())
                    object instance = null;
                    var service = CefCustomHandlerFakeTypes.GetHandlerType(enumKey);
                    var keyStr  = enumKey.EnumToString();
                        if (IoC.IsRegistered(service, keyStr))
                            instance = IoC.GetInstance(service, keyStr);
                    catch (Exception exception)
                        Log.Error(exception);
                    switch (enumKey)
                    case CefHandlerKey.LifeSpanHandler:
                        if (instance is ILifeSpanHandler lifeSpanHandler)
                            browser.LifeSpanHandler = lifeSpanHandler;
                            browser.LifeSpanHandler = new CefSharpLifeSpanHandler();
                        break;
                    case CefHandlerKey.LoadHandler:
                        if (instance is ILoadHandler loadHandler)
                            browser.LoadHandler = loadHandler;
                        break;
                    case CefHandlerKey.RequestHandler:
                        if (instance is IRequestHandler requestHandler)
                            browser.RequestHandler = requestHandler;
                            browser.RequestHandler = new CefSharpRequestHandler();
                        break;
                    case CefHandlerKey.DisplayHandler:
                        if (instance is IDisplayHandler displayHandler)
                            browser.DisplayHandler = displayHandler;
                        break;
                    case CefHandlerKey.ContextMenuHandler:
                        if (instance is IContextMenuHandler contextMenuHandler)
                            browser.MenuHandler = contextMenuHandler;
                            browser.MenuHandler = new CefSharpContextMenuHandler();
                        break;
                    case CefHandlerKey.FocusHandler:
                        if (instance is IFocusHandler focusHandler)
                            browser.FocusHandler = focusHandler;
                        break;
                    case CefHandlerKey.KeyboardHandler:
                        if (instance is IKeyboardHandler keyboardHandler)
                            browser.KeyboardHandler = keyboardHandler;
                        break;
                    case CefHandlerKey.JsDialogHandler:
                        if (instance is IJsDialogHandler jsDialogHandler)
                            browser.JsDialogHandler = jsDialogHandler;
                        break;
                    case CefHandlerKey.DialogHandler:
                        if (instance is IDialogHandler dialogHandler)
                            browser.DialogHandler = dialogHandler;
                        break;
                    case CefHandlerKey.DragHandler:
                        if (instance is IDragHandler dragHandler)
                            browser.DragHandler = dragHandler;
                        break;
                    case CefHandlerKey.DownloadHandler:
                        if (instance is IDownloadHandler downloadHandler)
                            browser.DownloadHandler = downloadHandler;
                        break;
                    case CefHandlerKey.FindHandler:
                        if (instance is IFindHandler findHandler)
                            browser.FindHandler = findHandler;
                        break;
            catch (Exception exception)
                Log.Error(exception);
        }
示例#51
文件: DefaultFocusHandler.cs gleox/CefSharp
 public DefaultFocusHandler(ChromiumWebBrowser browser)
     this.browser = browser;
 }
示例#52
文件: ChromiumWebBrowserExtension.cs zhh007/Chromely
        /// <summary>
        /// The set event handlers.
        /// </summary>
        /// <param name="browser">
        /// The browser.
        /// </param>
        public static void SetEventHandlers(this ChromiumWebBrowser browser)
                foreach (var enumKey in CefEventHandlerFakeTypes.GetAllEventHandlerKeys())
                    object instance = null;
                    var service = CefEventHandlerFakeTypes.GetHandlerType(enumKey);
                    var keyStr  = enumKey.EnumToString();
                        if (IoC.IsRegistered(service, keyStr))
                            instance = IoC.GetInstance(service, keyStr);
                    catch (Exception exception)
                        Log.Error(exception);
                    switch (enumKey)
                    case CefEventKey.None:
                        break;
                    case CefEventKey.FrameLoadStart:
                        if (instance is ChromelyEventHandler <FrameLoadStartEventArgs> frameLoadStart)
                            browser.FrameLoadStart += frameLoadStart.Handler;
                        break;
                    case CefEventKey.AddressChanged:
                        if (instance is ChromelyEventHandler <AddressChangedEventArgs> addressChanged)
                            browser.AddressChanged += addressChanged.Handler;
                        break;
                    case CefEventKey.TitleChanged:
                        if (instance is ChromelyEventHandler <TitleChangedEventArgs> titleChanged)
                            browser.TitleChanged += titleChanged.Handler;
                        break;
                    case CefEventKey.FrameLoadEnd:
                        if (instance is ChromelyEventHandler <FrameLoadEndEventArgs> frameLoadEnd)
                            browser.FrameLoadEnd += frameLoadEnd.Handler;
                        break;
                    case CefEventKey.LoadingStateChanged:
                        if (instance is ChromelyEventHandler <LoadingStateChangedEventArgs> loadingStateChanged)
                            browser.LoadingStateChanged += loadingStateChanged.Handler;
                        break;
                    case CefEventKey.ConsoleMessage:
                        if (instance is ChromelyEventHandler <ConsoleMessageEventArgs> consoleMessage)
                            browser.ConsoleMessage += consoleMessage.Handler;
                        break;
                    case CefEventKey.StatusMessage:
                        if (instance is ChromelyEventHandler <StatusMessageEventArgs> statusMessage)
                            browser.StatusMessage += statusMessage.Handler;
                        break;
                    case CefEventKey.LoadError:
                        if (instance is ChromelyEventHandler <LoadErrorEventArgs> loadError)
                            browser.LoadError += loadError.Handler;
                        break;
            catch (Exception exception)
                Log.Error(exception);
        }
示例#53
0
        static void Main(string[] args)
            Console.WriteLine("PulsoidRecoder バージョン0.1 (c)WSOFT 2020");
            Console.CancelKeyPress += Console_CancelKeyPress;
            CefSettings settings = new CefSettings();
            settings.Locale             = "ja";
            settings.LogSeverity        = LogSeverity.Disable;
            settings.AcceptLanguageList = "ja-JP";
            Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null);
            bool breakflag = false;
            while (!breakflag)
                Console.WriteLine("PulsoidRecoder メインメニュー");
                Console.WriteLine("実行したい操作を選択してください");
                Console.Write("[R:記録モード / E:エクセル出力モード / V:閲覧モード / L:オープンソースライセンスを表示 / QまたはEsc:終了]");
                switch (Console.ReadKey().Key)
                case ConsoleKey.Escape:
                    breakflag = true;
                    break;
                case ConsoleKey.Q:
                    breakflag = true;
                    break;
                case ConsoleKey.L:
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("オープンソースライセンス");
                    Console.WriteLine("PulsoidRecoderはこれらのオープンソースソフトウェアによって実現しました");
                    Console.WriteLine();
                    Console.WriteLine(PulsoidRecoder.Properties.Resources.Licences);
                    Console.WriteLine();
                    break;
                case ConsoleKey.E:
                    Console.WriteLine("読み込むファイル名を入力してください");
                    Console.Write("ファイルパス>");
                    string filepath = Console.ReadLine();
                    Console.Write("解析しています.");
                    BPMRecordCollection collection = LoadFile(filepath);
                    XLWorkbook          workbook   = new XLWorkbook();
                    IXLWorksheet        worksheet  = workbook.AddWorksheet();
                    worksheet.Name = "Pulseroid RecordLog";
                    IXLCell c = worksheet.Cell(1, 1);
                    c.Value = "日時";
                    IXLCell c1 = worksheet.Cell(1, 2);
                    c.Value = "心拍数";
                    IXLCell c2 = worksheet.Cell(1, 3);
                    c.Value = "最高心拍数";
                    IXLCell c3 = worksheet.Cell(1, 4);
                    c.Value = "平均心拍数";
                    IXLCell c4 = worksheet.Cell(1, 5);
                    c.Value = "最低心拍数";
                    IXLCell c5 = worksheet.Cell(2, 3);
                    c.Value = collection.Maxbpm;
                    IXLCell c6 = worksheet.Cell(2, 4);
                    c.Value = collection.Avgbpm;
                    IXLCell c7 = worksheet.Cell(2, 5);
                    c.Value = collection.Minbpm;
                    int cx    = 2;
                    int count = 0;
                    foreach (BPMRecord bpm in collection.Records)
                        IXLCell x = worksheet.Cell(cx, 1);
                        x.Value = bpm.Month + "/" + bpm.Day + " " + bpm.Hour + ":" + bpm.Minute + ":" + bpm.Second;
                        IXLCell x2 = worksheet.Cell(cx, 2);
                        x2.Value = bpm.BPM;
                        count++;
                        if (count == 60)
                            Console.Write(".");
                            count = 0;
                        cx++;
                    Console.WriteLine();
                    Console.WriteLine("解析完了");
                    Console.WriteLine("保存先を入力してください");
                    Console.Write("ファイルパス(.xlsx)>");
                    string savefilepath = Console.ReadLine();
                    if (Path.GetExtension(savefilepath) != ".xlsx")
                        savefilepath += ".xlsx";
                    Console.WriteLine("保存しています...");
                    workbook.SaveAs(savefilepath);
                    Console.WriteLine("保存完了");
                    break;
                case ConsoleKey.V:
                    Console.WriteLine("読み込むファイル名を入力してください");
                    Console.Write("ファイルパス>");
                    string filepath = Console.ReadLine();
                    BPMRecordCollection collection = LoadFile(filepath);
                    Console.WriteLine("記録:" + collection.Records.Length + "個 最高心拍数:" + collection.Maxbpm + "BPM 平均心拍数:" + collection.Avgbpm + "BPM 最低心拍数:" + collection.Minbpm + "BPM");
                    Console.WriteLine();
                    foreach (BPMRecord bpm in collection.Records)
                        Console.WriteLine(bpm.Month + "/" + bpm.Day + " " + bpm.Hour + ":" + bpm.Minute + ":" + bpm.Second + "  " + bpm.BPM + "BPM");
                    break;
                case ConsoleKey.R:
                    Console.WriteLine();
                    string WidetUrl = "";
                    Console.WriteLine("PulsoidのウィジェットUrlを入力してください");
                    Console.Write("URL>");
                    WidetUrl = Console.ReadLine();
                    int span = 1;
                    Console.WriteLine("何秒おきに記録するか設定してください");
                    Console.Write("時間(秒)>");
                    int.TryParse(Console.ReadLine(), out span);
                    if (span < 1)
                        span = 1;
                    string cachePath       = Path.GetFullPath("cache");
                    var    browserSettings = new BrowserSettings();
                    //毎秒一枚更新されればOK
                    browserSettings.WindowlessFrameRate = 1;
                    var requestContextSettings = new RequestContextSettings {
                        CachePath = cachePath
                    using (var requestContext = new RequestContext(requestContextSettings))
                        using (var browser = new ChromiumWebBrowser("", browserSettings, requestContext))
                            List <BPMRecord> records = new List <BPMRecord>();
                            //起動中は待機
                            Console.WriteLine("ブラウザを初期化しています");
                            while (!browser.IsBrowserInitialized)
                            Console.WriteLine("ページを準備しています");
                            browser.Load(WidetUrl);
                            //読み込み中は待機
                            Console.WriteLine("読み込んでいます");
                            while (browser.IsLoading)
                            Console.WriteLine("心拍表示を待機しています");
                            //BPMが表示されていない間は待機
                            while (GetBPM(browser) == 0)
                            int    maxbpm   = 0;
                            int    minbpm   = 999;
                            double bpmcount = 0;
                            int cct = Console.CursorTop;
                            int ccl = Console.CursorLeft;
                            Console.WriteLine("[***BPM  0秒]");
                            //記録スタート
                            while (true)
                                int bpm = GetBPM(browser);
                                if (maxbpm < bpm)
                                    maxbpm = bpm;
                                if (minbpm > bpm)
                                    minbpm = bpm;
                                bpmcount += bpm;
                                records.Add(new BPMRecord(DateTime.Now, bpm));
                                Task.Run(() =>
                                        Console.SetCursorPosition(ccl, cct);
                                        Console.WriteLine("[ " + bpm + "BPM  最大:" + maxbpm + "BPM 平均:" + (int)(bpmcount / records.Count) + "BPM 最小:" + minbpm + "BPM " + records.Count + "個の記録 ]");
                                if (preseCancel)
                                    break;
                                Thread.Sleep(span * 1000);
                            Console.WriteLine("記録を終了しました");
                            Console.WriteLine("記録の保存先を入力してください");
                            Console.Write("ファイルパス>");
                            string savepath = Console.ReadLine();
                            Console.WriteLine("保存しています...");
                            SaveFile(new BPMRecordCollection(records.ToArray(), maxbpm, minbpm, (int)(bpmcount / records.Count)), savepath);
                            Console.WriteLine("保存完了");
                    break;
        }