Example #1
0
        bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            if (commandId == (CefMenuCommand)26501)
            {
                browser.GetHost().ShowDevTools();
                return true;
            }
            if (commandId == (CefMenuCommand)26502)
            {
                browser.GetHost().CloseDevTools();
                return true;
            }

            return false;
        }
Example #2
0
 internal void NotifyMoveOrResize()
 {
     if (IsBrowserInitialized)
     {
         _browser?.GetHost()?.NotifyMoveOrResizeStarted();
     }
 }
Example #3
0
        /// <inheritdoc/>
        protected override void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser)
        {
            if (browser.IsPopup)
            {
                var windowHandle = browser.GetHost().GetWindowHandle();

                //WinForms will kindly lookup the child control from it's handle
                //If no parentControl then likely it's a native popup created by CEF
                //(Devtools by default will open as a popup, at this point the Url hasn't been set, so
                // we're going with this assumption as it fits the use case currently)
                var control = Control.FromChildHandle(windowHandle) as ChromiumHostControl;

                //If control is null then we'll treat as a native popup (do nothing)
                //If control is disposed there's nothing for us to do either.
                if (control != null && !control.IsDisposed)
                {
                    control.BrowserHwnd = windowHandle;

                    control.InvokeOnUiThreadIfRequired(() =>
                    {
                        var interceptor     = new ParentFormMessageInterceptor(control);
                        interceptor.Moving += (sender, args) =>
                        {
                            if (!browser.IsDisposed)
                            {
                                browser?.GetHost()?.NotifyMoveOrResizeStarted();
                            }
                        };

                        popupParentFormMessageInterceptors.Add(browser.Identifier, interceptor);
                    });
                }
            }
        }
Example #4
0
        /// <summary>
        /// Asynchronously prints the current browser contents to the PDF file specified.
        /// The caller is responsible for deleting the file when done.
        /// </summary>
        /// <param name="cefBrowser">The <see cref="IBrowser"/> object this method extends.</param>
        /// <param name="path">Output file location.</param>
        /// <param name="settings">Print Settings.</param>
        /// <returns>A task that represents the asynchronous print operation.
        /// The result is true on success or false on failure to generate the Pdf.</returns>
        public static Task <bool> PrintToPdfAsync(this IBrowser cefBrowser, string path, PdfPrintSettings settings = null)
        {
            var host = cefBrowser.GetHost();

            ThrowExceptionIfBrowserHostNull(host);

            var callback = new TaskPrintToPdfCallback();

            host.PrintToPdf(path, settings, callback);

            return(callback.Task);
        }
Example #5
0
        /// <summary>
        /// Called after browser created.
        /// </summary>
        /// <param name="browser">The browser.</param>
        partial void OnAfterBrowserCreated(IBrowser browser)
        {
            BrowserCore = browser;
            BrowserHwnd = browser.GetHost().GetWindowHandle();

            // By the time this callback gets called, this control
            // is most likely hooked into a browser Form of some sort.
            // (Which is what ParentFormMessageInterceptor relies on.)
            // Ensure the ParentFormMessageInterceptor construction occurs on the WinForms UI thread:
            if (UseParentFormMessageInterceptor)
            {
                this.InvokeOnUiThreadIfRequired(() =>
                {
                    parentFormMessageInterceptor         = new ParentFormMessageInterceptor(this);
                    parentFormMessageInterceptor.Moving += (sender, args) =>
                    {
                        if (IsBrowserInitialized && !IsDisposed)
                        {
                            browser?.GetHost()?.NotifyMoveOrResizeStarted();
                        }
                    };
                });
            }

            ResizeBrowser(Width, Height);

            //If Load was called after the call to CreateBrowser we'll call Load
            //on the MainFrame
            if (!initialAddressLoaded && !string.IsNullOrEmpty(Address))
            {
                browser.MainFrame.LoadUrl(Address);
            }

            if (initialFocus)
            {
                browser.GetHost()?.SetFocus(true);
            }

            RaiseIsBrowserInitializedChangedEvent();
        }
Example #6
0
        bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            ////命令的执行
            if (commandId == (CefMenuCommand)26501)
            {
                browser.GetHost().ShowDevTools();
                return(true);
            }
            if (commandId == (CefMenuCommand)26502)
            {
                browser.GetHost().CloseDevTools();
                return(true);
            }

            if (commandId == CefMenuCommand.Reload)
            {
                browser.Reload();
                return(true);
            }
            if (commandId == CefMenuCommand.Back)
            {
                browser.GoBack();
                return(true);
            }
            if (commandId == CefMenuCommand.Forward)
            {
                browser.GoForward();
                return(true);
            }
            if (commandId == CefMenuCommand.Print)
            {
                browser.Print();
                return(true);
            }
            if (commandId == CefMenuCommand.Copy)
            {
                return(true);
            }
            return(false);
        }
        public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            // React to the first ID (show dev tools method)
            // working but not useful as some pages disable right click
            //if (commandId == (CefMenuCommand)26501)
            //{
            //    browser.GetHost().ShowDevTools();
            //    return true;
            //}
            if (commandId == (CefMenuCommand)26501) //Export as PDF
            {
                string filepath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
                //ChromiumWebBrowser current_browser = (ChromiumWebBrowser)browserControl;
                //current_browser.PrintToPdfAsync(filepath, null);
                printToPdfCallback callback = new printToPdfCallback();
                browser.GetHost().PrintToPdf(filepath, null, callback);
                return(true);
            }

            if (commandId == (CefMenuCommand)26504) //Copy link address
            {
                string url = clean_url(parameters.LinkUrl);

                General.Copy2Clipboard(url);
                return(true);
            }

            // React to the second ID (show dev tools method)
            //                  Open in new tab w/ cookies --                   Open in new tab --          Open in default browser
            if (commandId == (CefMenuCommand)26502 || commandId == (CefMenuCommand)26503 || commandId == (CefMenuCommand)26505)
            {
                if (!string.IsNullOrEmpty(parameters.LinkUrl) && parameters.LinkUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                {
                    if (commandId == (CefMenuCommand)26505)
                    {
                        //System.Diagnostics.Process.Start(clean_url(parameters.LinkUrl));
                        ChromiumWebBrowser current_browser     = (ChromiumWebBrowser)browserControl;
                        CefControl1        current_CEF_comtrol = (CefControl1)current_browser.Parent;
                        current_CEF_comtrol.open_to_browser(clean_url(parameters.LinkUrl));
                    }
                    else
                    {
                        ChromiumWebBrowser current_browser     = (ChromiumWebBrowser)browserControl;
                        CefControl1        current_CEF_comtrol = (CefControl1)current_browser.Parent;
                        current_CEF_comtrol.open_child_tab(parameters.LinkUrl, commandId == (CefMenuCommand)26502);
                    }
                }
                //browser.GetHost().CloseDevTools();
                return(true);
            }
            return(false);
        }
Example #8
0
        bool ILifeSpanHandler.DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
        {
            var windowHandle = browser.GetHost().GetWindowHandle();
            var webBrowser   = (ChromiumWebBrowser)chromiumWebBrowser;

            if (browser.MainFrame.Url.Equals("devtools://devtools/devtools_app.html"))
            {
                var parentControl = Control.FromChildHandle(windowHandle);

                //If the windowHandle doesn't have a matching WinForms control
                //then we assume it's hosted by a native popup window (the default)
                //and allow the default behaviour which sends a WM_CLOSE message
                if (parentControl == null)
                {
                    return(false);
                }

                //Dispose of the parent control we used to host DevTools, this will release the DevTools window handle
                //and the ILifeSpanHandler.OnBeforeClose() will be call after.
                webBrowser.Invoke(new Action(() =>
                {
                    parentControl.Dispose();
                }));

                return(true);
            }

            if (openPopupsAsTabs)
            {
                //If browser is disposed or the handle has been released then we don't
                //need to remove the tab (likely removed from menu)
                if (!webBrowser.IsDisposed && webBrowser.IsHandleCreated)
                {
                    /* todo
                     * webBrowser.Invoke(new Action(() =>
                     * {
                     *  if (webBrowser.FindForm() is BrowserForm owner)
                     *  {
                     *      owner.RemoveTab(windowHandle);
                     *  }
                     * }));
                     */
                }

                //return true here to handle closing yourself (no WM_CLOSE will be sent).
                return(true);
            }

            //The default CEF behaviour (return false) will send a OS close notification (e.g. WM_CLOSE).
            //See the doc for this method for full details.
            return(false);
        }
Example #9
0
        public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            // React to the first ID (show dev tools method)
            if (commandId == (CefMenuCommand)26501)
            {
                browser.GetHost().ShowDevTools();
                return(true);
            }

            // React to the second ID (show dev tools method)
            if (commandId == (CefMenuCommand)26502)
            {
                browser.GetHost().CloseDevTools();
                return(true);
            }

            // Any new item should be handled through a new if statement


            // Return false should ignore the selected option of the user !
            return(false);
        }
Example #10
0
        private void OnBeforeDownloadFired(object sender, DownloadItem e)
        {
            //DownloadHandler downloadHandler = (DownloadHandler)sender;
            IBrowser browser = (IBrowser)sender;

            if (browser.IsPopup)
            {
                //解决下载弹出框问题 neo 2017年1月24日15:51:39
                IntPtr handle = browser.GetHost().GetWindowHandle(); //得到窗口的句柄
                ShowWindow(handle, 0);                               //不显示下载对话框页面
            }
            //this.UpdateDownloadAction("OnBeforeDownload", e);
        }
Example #11
0
        private void CreateBrowser()
        {
            browserCreated = true;

            if (((IWebBrowserInternal)this).HasParent == false)
            {
                if (IsBrowserInitialized == false || browser == null)
                {
                    var windowInfo = new WindowInfo();
                    windowInfo.SetAsChild(Handle);

                    //TODO: Revert temp workaround for default url not loading
                    managedCefBrowserAdapter.CreateBrowser(windowInfo, BrowserSettings, (RequestContext)RequestContext, null);
                }
                else
                {
                    //If the browser already exists we'll reparent it to the new Handle
                    var browserHandle = browser.GetHost().GetWindowHandle();
                    NativeMethodWrapper.SetWindowParent(browserHandle, Handle);
                }
            }
        }
Example #12
0
        private void CreateBrowser()
        {
            browserCreated = true;

            if (((IWebBrowserInternal)this).HasParent == false)
            {
                if (IsBrowserInitialized == false || browser == null)
                {
                    var windowInfo = CreateBrowserWindowInfo(Handle);

                    managedCefBrowserAdapter.CreateBrowser(windowInfo, browserSettings as BrowserSettings, requestContext as RequestContext, Address);

                    browserSettings = null;
                }
                else
                {
                    //If the browser already exists we'll reparent it to the new Handle
                    var browserHandle = browser.GetHost().GetWindowHandle();
                    NativeMethodWrapper.SetWindowParent(browserHandle, Handle);
                }
            }
        }
Example #13
0
        bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            if ((int)commandId == ShowDevTools)
            {
                browser.ShowDevTools();
            }
            if ((int)commandId == CloseDevTools)
            {
                browser.CloseDevTools();
            }
            if ((int)commandId == SaveImageAs)
            {
                browser.GetHost().StartDownload(parameters.SourceUrl);
            }
            if ((int)commandId == CopyImage)
            {
                // Clipboard.SetImage(parameters.HasImageContents);
            }
            if ((int)commandId == SaveLinkAs)
            {
                browser.GetHost().StartDownload(parameters.LinkUrl);
            }

            if ((int)commandId == CopyLinkAddress)
            {
                Clipboard.SetText(parameters.LinkUrl);
            }


            if ((int)commandId == SaveAsPdf)
            {
                PdfPrintSettings settings = new PdfPrintSettings();
                settings.Landscape          = true;
                settings.BackgroundsEnabled = false;

                browser.PrintToPdfAsync(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\TorBrowser.pdf", settings);
            }
            return(false);
        }
Example #14
0
        /// <inheritdoc/>
        protected override void OnGotFocus(EventArgs e)
        {
            if (IsBrowserInitialized)
            {
                browser.GetHost().SetFocus(true);
            }
            else
            {
                initialFocus = true;
            }

            base.OnGotFocus(e);
        }
        /// <summary>
        /// Chromium'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>
        /// <param name="browser">IBrowser instance</param>
        /// <param name="chromerRenderWidgetHostHandle">Handle of the child HWND with the name <see cref="ChromeRenderWidgetHostClassName"/></param>
        /// <returns>returns true if the HWND was found otherwise false.</returns>
        public static bool TryFindHandle(IBrowser browser, out IntPtr chromerRenderWidgetHostHandle)
        {
            var host = browser.GetHost();

            if (host == null)
            {
                throw new Exception("IBrowserHost is null, you've likely call this method before the underlying browser has been created.");
            }

            var hwnd = host.GetWindowHandle();

            return(TryFindHandle(hwnd, ChromeRenderWidgetHostClassName, out chromerRenderWidgetHostHandle));
        }
Example #16
0
        /// <summary>
        /// Gets a new Instance of the DevTools client
        /// </summary>
        /// <param name="browser">the IBrowser instance</param>
        /// <returns>DevToolsClient</returns>
        public static DevToolsClient GetDevToolsClient(this IBrowser browser)
        {
            var browserHost = browser.GetHost();

            WebBrowserExtensions.ThrowExceptionIfBrowserHostNull(browserHost);

            var devToolsClient = new DevToolsClient(browser);

            var observerRegistration = browserHost.AddDevToolsMessageObserver(devToolsClient);

            devToolsClient.SetDevToolsObserverRegistration(observerRegistration);

            return(devToolsClient);
        }
    public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
    {
        // React to the first ID (show dev tools method)
        if (commandId == (CefMenuCommand)26505)
        {
            browser.GetHost().ShowDevTools();
            return(true);
        }
        if (commandId == (CefMenuCommand)26504)
        {
            if (parameters.LinkUrl.Length > 0)
            {
                Clipboard.SetText(parameters.LinkUrl);
            }
            if (parameters.MediaType == ContextMenuMediaType.Image)
            {
                Clipboard.SetText(parameters.SourceUrl);

                string subPath = @"C:\temp";

                string fn = @"C:\temp\image.jpeg";

                System.IO.Directory.CreateDirectory(subPath);

                SaveImage(parameters.SourceUrl, fn, ImageFormat.Jpeg);

                Process.Start(fn);
            }
            MessageBox.Show("Saved as Image");
            return(true);
        }
        if (commandId == (CefMenuCommand)113) // Copy
        {
            if (parameters.LinkUrl.Length > 0)
            {
                Clipboard.SetText(parameters.LinkUrl);
            }
            if (parameters.MediaType == ContextMenuMediaType.Image)
            {
                Clipboard.SetText(parameters.SourceUrl);
            }
        }


        // Any new item should be handled through a new if statement


        // Return false should ignore the selected option of the user !
        return(false);
    }
Example #18
0
 public bool OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey)
 {
     //对按键的处理
     switch (windowsKeyCode)
     {
     case 123:     //功能键 F12 的KeyCode
         if (type.Equals(KeyType.RawKeyDown))
         {
             browser.GetHost().ShowDevTools();
         }
         break;
     }
     return(false);
 }
Example #19
0
        bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            if ((int)commandId == ShowDevTools)
            {
                browser.ShowDevTools();
            }
            if ((int)commandId == CloseDevTools)
            {
                browser.CloseDevTools();
            }
            if ((int)commandId == SaveImageAs)
            {
                browser.GetHost().StartDownload(parameters.SourceUrl);
            }
            if ((int)commandId == SaveLinkAs)
            {
                browser.GetHost().StartDownload(parameters.LinkUrl);
            }
            if ((int)commandId == OpenLinkInNewTab)
            {
                ChromiumWebBrowser newBrowser = myForm.AddNewBrowserTab(parameters.LinkUrl, false);
            }
            if ((int)commandId == CopyLinkAddress)
            {
                Clipboard.SetText(parameters.LinkUrl);
            }

            /* if ((int)commandId == SaveAsPdf)
             * {
             *   PdfPrintSettings settings = new PdfPrintSettings();
             *   settings.Landscape = true;
             *   settings.BackgroundsEnabled = false;
             *   browser.PrintToPdfAsync(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\SharpBrowser.pdf", settings);
             * }*/

            return(false);
        }
        private void InitialLoad(bool?isLoading, CefErrorCode?errorCode)
        {
            if (IsDisposed)
            {
                initialLoadAction = null;

                initialLoadTaskCompletionSource.TrySetCanceled();

                return;
            }

            if (isLoading.HasValue)
            {
                if (isLoading.Value)
                {
                    return;
                }

                initialLoadAction = null;

                var host = browser?.GetHost();

                var navEntry = host?.GetVisibleNavigationEntry();

                int statusCode = navEntry?.HttpStatusCode ?? -1;

                //By default 0 is some sort of error, we map that to -1
                //so that it's clearer that something failed.
                if (statusCode == 0)
                {
                    statusCode = -1;
                }

                initialLoadTaskCompletionSource.TrySetResultAsync(new LoadUrlAsyncResponse(CefErrorCode.None, statusCode));
            }
            else if (errorCode.HasValue)
            {
                //Actions that trigger a download will raise an aborted error.
                //Generally speaking Aborted is safe to ignore
                if (errorCode == CefErrorCode.Aborted)
                {
                    return;
                }

                initialLoadAction = null;

                initialLoadTaskCompletionSource.TrySetResultAsync(new LoadUrlAsyncResponse(errorCode.Value, -1));
            }
        }
Example #21
0
        /// <summary>
        /// Execute a method call over the DevTools protocol. This method can be called on any thread.
        /// See the DevTools protocol documentation at https://chromedevtools.github.io/devtools-protocol/ for details
        /// of supported methods and the expected <paramref name="parameters"/> dictionary contents.
        /// </summary>
        /// <typeparam name="T">The type into which the result will be deserialzed.</typeparam>
        /// <param name="method">is the method name</param>
        /// <param name="parameters">are the method parameters represented as a dictionary,
        /// which may be empty.</param>
        /// <returns>return a Task that can be awaited to obtain the method result</returns>
        public Task <T> ExecuteDevToolsMethodAsync <T>(string method, IDictionary <string, object> parameters = null) where T : DevToolsDomainResponseBase
        {
            if (browser == null || browser.IsDisposed)
            {
                //TODO: Queue up commands where possible
                throw new ObjectDisposedException(nameof(IBrowser));
            }

            var messageId = Interlocked.Increment(ref lastMessageId);

            var taskCompletionSource = new TaskCompletionSource <T>();

            var methodResultContext = new DevToolsMethodResponseContext(
                type: typeof(T),
                setResult: o => taskCompletionSource.TrySetResult((T)o),
                setException: taskCompletionSource.TrySetException,
                syncContext: CaptureSyncContext ? SynchronizationContext.Current : SyncContext
                );

            if (!queuedCommandResults.TryAdd(messageId, methodResultContext))
            {
                throw new DevToolsClientException(string.Format("Unable to add MessageId {0} to queuedCommandResults ConcurrentDictionary.", messageId));
            }

            var browserHost = browser.GetHost();

            //Currently on CEF UI Thread we can directly execute
            if (CefThread.CurrentlyOnUiThread)
            {
                ExecuteDevToolsMethod(browserHost, messageId, method, parameters, methodResultContext);
            }
            //ExecuteDevToolsMethod can only be called on the CEF UI Thread
            else if (CefThread.CanExecuteOnUiThread)
            {
                CefThread.ExecuteOnUiThread(() =>
                {
                    ExecuteDevToolsMethod(browserHost, messageId, method, parameters, methodResultContext);
                    return((object)null);
                });
            }
            else
            {
                queuedCommandResults.TryRemove(messageId, out methodResultContext);
                throw new DevToolsClientException("Unable to invoke ExecuteDevToolsMethod on CEF UI Thread.");
            }

            return(taskCompletionSource.Task);
        }
        /// <summary>
        /// Gets the <see cref="ChromiumHostControl"/> or <see cref="ChromiumWebBrowser"/> associated with
        /// a specific <see cref="IBrowser"/> instance.
        /// </summary>
        /// <param name="browser">browser</param>
        /// <returns>returns the assocaited <see cref="ChromiumHostControl"/> or <see cref="ChromiumWebBrowser"/> or null if Disposed or no host found.</returns>
        public static T FromBrowser <T>(IBrowser browser) where T : ChromiumHostControlBase
        {
            if (browser.IsDisposed)
            {
                return(null);
            }

            var windowHandle = browser.GetHost().GetWindowHandle();

            if (windowHandle == IntPtr.Zero)
            {
                return(null);
            }

            var control = Control.FromChildHandle(windowHandle) as T;

            return(control);
        }
Example #23
0
 public void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser)
 {
     try
     {
         var windHandler = browser.GetHost().GetWindowHandle();
         // winformのアイコンを変更する
         using (var icon = new Icon(Directory.GetCurrentDirectory() + @"\ChangePopupIconSample\myIcon.ico"))
         {
             SendMessage(windHandler, WM_SETICON, ICON_BIG, icon.Handle);
         }
         // 画面サイズを最大化する
         ShowWindowAsync(windHandler, SIZE_MAXIMIZED);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Example #24
0
        /// <summary>
        /// Gets the <see cref="ChromiumHostControl"/> associated with
        /// a specific <see cref="IBrowser"/> instance.
        /// </summary>
        /// <param name="browser">browser</param>
        /// <returns>returns the assocaited <see cref="ChromiumHostControl"/> or null if Disposed or no host found.</returns>
        public static ChromiumHostControl FromBrowser(IBrowser browser)
        {
            if (browser.IsDisposed)
            {
                return(null);
            }

            var windowHandle = browser.GetHost().GetWindowHandle();

            if (windowHandle == IntPtr.Zero)
            {
                return(null);
            }

            var control = Control.FromChildHandle(windowHandle) as ChromiumHostControl;

            return(control);
        }
Example #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChromiumWebBrowser"/> class.
 /// </summary>
 /// <param name="parent">The parent handle.</param>
 public void CreateBrowser(IntPtr parent)
 {
     if (((IWebBrowserInternal)this).HasParent == false)
     {
         if (IsBrowserInitialized == false || browser == null)
         {
             //TODO: Revert temp workaround for default url not loading
             RequestContext = Cef.GetGlobalRequestContext();
             browserCreated = true;
             managedCefBrowserAdapter.CreateBrowser(BrowserSettings, (RequestContext)RequestContext, parent, null);
         }
         else
         {
             //If the browser already exists we'll reparent it to the new Handle
             var browserHandle = browser.GetHost().GetWindowHandle();
             NativeMethodWrapper.SetWindowParent(browserHandle, parent);
         }
     }
 }
Example #26
0
        void ILifeSpanHandler.OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser)
        {
            if (browser.IsPopup)
            {
                var windowHandle = browser.GetHost().GetWindowHandle();

                //WinForms will kindly lookup the child control from it's handle
                //If no parentControl then likely it's a popup and has no parent handle
                //(Devtools by default will remain a popup, at this point the Url hasn't been set, so
                // we're going with this assumption as it fits the use case of this example)
                var parentControl = Control.FromChildHandle(windowHandle);

                if (parentControl != null)
                {
                    var interceptor = new PopupAsChildHelper(browser);

                    popupasChildHelpers.Add(browser.Identifier, interceptor);
                }
            }
        }
Example #27
0
        /// <summary>
        /// Called after browser created.
        /// </summary>
        /// <param name="browser">The browser.</param>
        void IWebBrowserInternal.OnAfterBrowserCreated(IBrowser browser)
        {
            if (IsDisposed || browser.IsDisposed)
            {
                return;
            }

            this.browser = browser;
            Interlocked.Exchange(ref browserInitialized, 1);

            // By the time this callback gets called, this control
            // is most likely hooked into a browser Form of some sort.
            // (Which is what ParentFormMessageInterceptor relies on.)
            // Ensure the ParentFormMessageInterceptor construction occurs on the WinForms UI thread:
            if (UseParentFormMessageInterceptor)
            {
                this.InvokeOnUiThreadIfRequired(() =>
                {
                    parentFormMessageInterceptor = new ParentFormMessageInterceptor(this);
                });
            }

            ResizeBrowser(Width, Height);

            //If Load was called after the call to CreateBrowser we'll call Load
            //on the MainFrame
            if (!initialAddressLoaded && !string.IsNullOrEmpty(Address))
            {
                browser.MainFrame.LoadUrl(Address);
            }

            if (initialFocus)
            {
                browser.GetHost()?.SetFocus(true);
            }

            IsBrowserInitializedChanged?.Invoke(this, EventArgs.Empty);
        }
Example #28
0
        /// <summary>
        /// Execute a method call over the DevTools protocol. This is a more structured
        /// version of SendDevToolsMessage. <see cref="ExecuteDevToolsMethod"/> can only be called on the
        /// CEF UI Thread, this method can be called on any thread.
        /// See the DevTools protocol documentation at https://chromedevtools.github.io/devtools-protocol/ for details
        /// of supported methods and the expected <paramref name="parameters"/> dictionary contents.
        /// See the SendDevToolsMessage documentation for additional usage information.
        /// </summary>
        /// <param name="browser">the browser instance</param>
        /// <param name="messageId">is an incremental number that uniquely identifies the message (pass 0 to have the next number assigned
        /// automatically based on previous values)</param>
        /// <param name="method">is the method name</param>
        /// <param name="parameters">are the method parameters represented as a dictionary,
        /// which may be empty.</param>
        /// <returns>return a Task that can be awaited to obtain the assigned message Id. If the message was
        /// unsuccessfully submitted for validation, this value will be 0.</returns>
        public static Task <int> ExecuteDevToolsMethodAsync(this IBrowser browser, int messageId, string method, IDictionary <string, object> parameters = null)
        {
            WebBrowserExtensions.ThrowExceptionIfBrowserNull(browser);

            var browserHost = browser.GetHost();

            WebBrowserExtensions.ThrowExceptionIfBrowserHostNull(browserHost);

            if (CefThread.CurrentlyOnUiThread)
            {
                return(Task.FromResult(browserHost.ExecuteDevToolsMethod(messageId, method, parameters)));
            }

            if (CefThread.CanExecuteOnUiThread)
            {
                return(CefThread.ExecuteOnUiThread(() =>
                {
                    return browserHost.ExecuteDevToolsMethod(messageId, method, parameters);
                }));
            }

            //CEF returns 0 to signify failure, we'll do the same.
            return(Task.FromResult(0));
        }
Example #29
0
        public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            int id = (int)commandId;

            if (id == auto)
            {
                frame.ExecuteJavaScriptAsync(File.ReadAllText(Js.autofill));
            }
            if (id == Search)
            {
                newtab(parameters.SelectionText);
            }
            if (id == DorkInTitle)
            {
                newtab("intitle:" + parameters.SelectionText);
            }
            if (id == DorkInUrl)
            {
                newtab("inurl:" + parameters.SelectionText);
            }
            if (id == DorkInText)
            {
                newtab("intext:" + parameters.SelectionText);
            }
            if (id == DorkSite)
            {
                newtab("site:" + parameters.SelectionText);
            }
            if (id == DorkLink)
            {
                newtab("link:" + parameters.SelectionText);
            }
            if (id == DorkFileType)
            {
                newtab("filetype:" + parameters.SelectionText);
            }
            if (id == DorkExt)
            {
                newtab("ext:" + parameters.SelectionText);
            }
            if (id == ShowDevTools)
            {
                browser.ShowDevTools();
            }
            if (id == CloseDevTools)
            {
                browser.CloseDevTools();
            }
            if (id == SaveImageAs)
            {
                browser.GetHost().StartDownload(parameters.SourceUrl);
            }
            if (id == SaveVideoAs)
            {
                browser.GetHost().StartDownload(parameters.SourceUrl);
            }
            if (id == SaveLinkAs)
            {
                browser.GetHost().StartDownload(parameters.PageUrl);
            }
            if (id == OpenLinkInNewTab)
            {
                string url;
                if (parameters.LinkUrl != "")
                {
                    url = parameters.LinkUrl;
                    myForm.InvokeOnParent(delegate() { myForm.AddNewBrowser(url); });
                }
                else
                {
                    url = parameters.SelectionText;
                    myForm.InvokeOnParent(delegate() { myForm.AddNewBrowser(url); });
                }
            }
            if (id == CopyLinkAddress)
            {
                Clipboard.SetText(parameters.LinkUrl);
            }
            if (id == CloseTab)
            {
                myForm.X.InvokeOnParent(delegate() { myForm.CloseActiveTab(); });
            }
            if (id == RefreshTab)
            {
                browser.Reload();
            }
            if (id == GetSource)
            {
                myForm.InvokeOnParent(delegate() { myForm.ViewSource(); });
            }

            return(false);
        }
Example #30
0
        bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            if ((int)commandId == ShowDevTools)
            {
                browser.ShowDevTools();
            }
            if ((int)commandId == CloseDevTools)
            {
                browser.CloseDevTools();
            }
            if ((int)commandId == SaveImageAs)
            {
                browser.GetHost().StartDownload(parameters.SourceUrl);
                return(true);
            }
            if ((int)commandId == SaveLinkAs)
            {
                browser.GetHost().StartDownload(parameters.LinkUrl);
                return(true);
            }
            if ((int)commandId == CopyLinkAddress)
            {
                Clipboard.SetText(parameters.LinkUrl);
            }

            if ((int)commandId == SaveAsPage)
            {
                browser.GetHost().StartDownload(parameters.PageUrl);

                return(true);
            }

            if ((int)commandId == CefSharpVersion)
            {
                browser.MainFrame.LoadUrl("chrome://chrome-urls/");
                return(true);
            }
            if ((int)commandId == CefSharpSupportedChromeExtensions)
            {
                browser.MainFrame.LoadUrl("chrome://extensions-support/");

                return(true);
            }
            if ((int)commandId == BaiduSearchChinese)
            {
                browser.MainFrame.LoadUrl("https://www.baidu.com/");

                return(true);
            }
            if ((int)commandId == GoogleSearchChinese)
            {
                browser.MainFrame.LoadUrl("https://www.google.com.hk");

                return(true);
            }
            if ((int)commandId == GoogleSearchEgypt)
            {
                browser.MainFrame.LoadUrl("https://www.google.com.eg");

                return(true);
            }
            if ((int)commandId == Back)
            {
                browser.GoBack();

                return(true);
            }
            if ((int)commandId == Forward)
            {
                browser.GoForward();

                return(true);
            }
            if ((int)commandId == Reload)
            {
                browser.MainFrame.Browser.Reload();

                return(true);
            }
            if ((int)commandId == Stop)
            {
                browser.StopLoad();

                return(true);
            }

            if ((int)commandId == Print)
            {
                browser.Print();
                return(true);
            }

            if ((int)commandId == ViewPageSource)
            {
                browser.MainFrame.ViewSource();

                return(true);
            }
            if ((int)commandId == Find)
            {
                browser.GetHost().Find(0, parameters.SelectionText, true, false, false);
                return(true);
            }


            if ((int)commandId == Undo)
            {
                browser.MainFrame.Undo();

                return(true);
            }
            if ((int)commandId == Redo)
            {
                browser.MainFrame.Redo();

                return(true);
            }

            if ((int)commandId == Cut)
            {
                browser.MainFrame.Cut();

                return(true);
            }
            if ((int)commandId == Copy)
            {
                browser.MainFrame.Copy();

                return(true);
            }
            if ((int)commandId == Paste)
            {
                browser.MainFrame.Paste();

                return(true);
            }
            if ((int)commandId == Delete)
            {
                browser.MainFrame.Delete();

                return(true);
            }
            if ((int)commandId == SelectAll)
            {
                browser.MainFrame.SelectAll();

                return(true);
            }

///
///

            if (commandId == (CefMenuCommand)5010)
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.FileName = "image.png";
                dialog.Filter   = "Png image (*.png)|*.png|ICO image (*.ico)|*.ico|Gif Image (*.gif)|*.gif|JPEG image (*.jpg)|*.jpg|SVG image (*.svg)|*.svg";

                var result = dialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    Console.WriteLine("writing to: " + dialog.FileName);

                    var wClient = new System.Net.WebClient();
                    wClient.DownloadFile(img, dialog.FileName);
                }
            }
            if (commandId == (CefMenuCommand)5011)
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.FileName = "Save All File Videos.mp4";
                dialog.Filter   = "MP4 (*.mp4)|*.mp4|MKV (*.mkv)|*.mkv|WEBM (*.webm)|*.webm|M3U (*.m3u)|*.m3u|All File (*.*)|*.*";

                var result = dialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    Console.WriteLine("writing to: " + dialog.FileName);

                    var wClient = new System.Net.WebClient();
                    wClient.DownloadFile(img, dialog.FileName);
                }
            }
            if (commandId == (CefMenuCommand)5012)
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.FileName = "Save All File Audio.mp3";
                dialog.Filter   = "MP3 (*.mp3)|*.mp3|Flac (*.flac)|*.flac|WAV (*.wav)|*.wav|All File (*.*)|*.*";

                var result = dialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    Console.WriteLine("writing to: " + dialog.FileName);

                    var wClient = new System.Net.WebClient();
                    wClient.DownloadFile(img, dialog.FileName);
                }
            }

            /*
             * if (commandId == (CefMenuCommand)5013)
             * {
             * }
             */
///
///

            if ((int)commandId == Good)
            {
                browser.GetHost().RequestContext.GetExtension(@"Resources\Extensions\");

                return(true);
            }


            return(false);
        }
Example #31
0
        public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            int id = (int)commandId;

            if (id == ShowDevTools)
            {
                browser.ShowDevTools();
            }
            if (id == CloseDevTools)
            {
                browser.CloseDevTools();
            }
            if (id == SaveImageAs)
            {
                browser.GetHost().StartDownload(parameters.SourceUrl);
            }
            if (id == SaveLinkAs)
            {
                browser.GetHost().StartDownload(parameters.LinkUrl);
            }
            if (id == OpenLinkInNewTab)
            {
                var url = parameters.LinkUrl;

                if (myForm.InvokeRequired)
                {
                    myForm.Invoke(new Action(() => myForm.CreateNewTab(url)));
                }
                else
                {
                    myForm.CreateNewTab(url);
                }


                return(true);
            }
            if (id == CopyLinkAddress)
            {
                Clipboard.SetText(parameters.LinkUrl);
            }
            if (id == CloseTab)
            {
                if (myForm.InvokeRequired)
                {
                    myForm.Invoke(new Action(() => myForm.CloseActiveTab()));
                }
                else
                {
                    myForm.CloseActiveTab();
                }
            }
            if (id == RefreshTab)
            {
                if (myForm.InvokeRequired)
                {
                    myForm.Invoke(new Action(() =>
                    {
                        myForm.RefreshActiveTab();
                    }));
                }
                else
                {
                    myForm.RefreshActiveTab();
                }
            }
            if (id == Favorite)
            {
                if (myForm.InvokeRequired)
                {
                    myForm.Invoke(new Action(() =>
                    {
                        myForm.AddBookmark();
                    }));
                }
                else
                {
                    myForm.AddBookmark();
                }
            }
            if (id == SaveAsPdf)
            {
                if (myForm.InvokeRequired)
                {
                    myForm.Invoke(new Action(() =>
                    {
                        myForm.SaveAsPDF();
                    }));
                }
                else
                {
                    myForm.SaveAsPDF();
                }
            }
            if (id == Print)
            {
                if (myForm.InvokeRequired)
                {
                    myForm.Invoke(new Action(() =>
                    {
                        myForm.Print();
                    }));
                }
                else
                {
                    myForm.Print();
                }
            }

            return(false);
        }