I know how to subscribe to the CoreWebview2.DownloadStarting event and use handled = true to stop the Download dialog from showing while a download (i.e. an image) is being made, but the problem is the DownloadStarting event never fires if you right click on a web page and choose "Save as" or "Print > Save as PDF", even though the Download dialog will appear as if a regular download was being made. Does anyone know any workaround for this?
My code:
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
if (webView != null)
webView.Dispose();
webView = new WebView2();
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting;
panel1.Controls.Add(webView);
webView.Dock = DockStyle.Fill;
webView.Source = new Uri("https://www.microsoft.com");
}
private void CoreWebView2_DownloadStarting(object sender, CoreWebView2DownloadStartingEventArgs e)
{
e.Handled = true;
}
I just found a solution:
subscribe to CoreWebView2.IsDefaultDownloadDialogOpenChanged event:
webView.CoreWebView2.IsDefaultDownloadDialogOpenChanged += webView_CoreWebView2_IsDefaultDownloadDialogOpenChanged;
Close the Download dialog if it's open:
private void webView_CoreWebView2_IsDefaultDownloadDialogOpenChanged(object sender, object e)
{
if (webView.CoreWebView2.IsDefaultDownloadDialogOpen) webView.CoreWebView2.CloseDefaultDownloadDialog();
}
I am trying to implement a simple web browser control in one of my apps. This is to help integrate a web app into a toolset i am creating.
The problem is, this web app absolutly loves popup windows....
When a popup is opened, it opens in an IE window which is not a child of the MDI Container form that my main window is part of.
How can i get any and all popups created by clicking links in my WebBrowser to be a child of my MDI container (similar to setting the MDIParent property of a form)?
Thanks in advance.
The web browser control supports the NewWindow event to get notified about a popup window. The Winforms wrapper however does not let you do much with it, you can only cancel the popup. The native COM wrapper permits passing back a new instance of the web browser, that instance will then be used to display the popup.
Taking advantage of this requires some work. For starters, use Project + Add Reference, Browse tab and select c:\windows\system32\shdocvw.dll. That adds a reference to the native COM interface.
Create a form that acts as the popup form. Drop a WebBrowser on it and make its code look similar to this:
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
public WebBrowser Browser {
get { return webBrowser1; }
}
}
The Browser property gives access to the browser that will be used to display the web page in the popup window.
Now back to the main form. Drop a WebBrowser on it and make its code look like this:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
webBrowser1.Url = new Uri("http://google.com");
}
SHDocVw.WebBrowser nativeBrowser;
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
nativeBrowser = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance;
nativeBrowser.NewWindow2 += nativeBrowser_NewWindow2;
}
protected override void OnFormClosing(FormClosingEventArgs e) {
nativeBrowser.NewWindow2 -= nativeBrowser_NewWindow2;
base.OnFormClosing(e);
}
void nativeBrowser_NewWindow2(ref object ppDisp, ref bool Cancel) {
var popup = new Form2();
popup.Show(this);
ppDisp = popup.Browser.ActiveXInstance;
}
}
The OnLoad method obtains a reference to the native COM interface, then subscribes an event handler to the NewWindow2 event. I made sure to unsubscribe that event in the FormClosing event handler, not 100% sure if that's necessary. Better safe then sorry.
The NewWindow2 event handler is the crux, note that the first argument allows passing back an untyped reference. That should be the native browser in the popup window. So I create an instance of Form2 and Show() it. Note the argument to Show(), that ensures that the popup is an owned window. Substitute this as necessary for your app, I assume you'd want to create an MDI child window in your case.
Do beware that this event doesn't fire for the window displayed when Javascript uses alert(). The browser doesn't treat that window as an HTML popup and doesn't use a browser window to display it so you cannot intercept or replace it.
I found that the best way to do this was to implement/sink the NewWindow3 event
Add the reference to c:\windows\system32\shdocvw.dll as mentioned in the other answers here.
Add event handler
SHDocVw.WebBrowser wbCOMmain = (SHDocVw.WebBrowser)webbrowser.ActiveXInstance;
wbCOMmain.NewWindow3 += wbCOMmain_NewWindow3;
Event method
void wbCOMmain_NewWindow3(ref object ppDisp,
ref bool Cancel,
uint dwFlags,
string bstrUrlContext,
string bstrUrl)
{
// bstrUrl is the url being navigated to
Cancel = true; // stop the navigation
// Do whatever else you want to do with that URL
// open in the same browser or new browser, etc.
}
Set "Embed Interop Types" for the "Interop.SHDocVw" assembly to false
Set the "local copy" to true.
Source for that help MSDN Post
Refining Hans answer, you can derive the WebBrowser for accessing the COM without adding the reference. It is by using the unpublished Winforms WebBrowser.AttachInterface and DetachInterface methods.
More elaborated here.
Here is the code:
Usage (change your WebBrowser instance to WebBrowserNewWindow2)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.webBrowser1.NewWindow2 += webBrowser_NewWindow2;
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
webBrowser1.NewWindow2 -= webBrowser_NewWindow2;
base.OnFormClosing(e);
}
void webBrowser_NewWindow2(object sender, WebBrowserNewWindow2EventArgs e)
{
var popup = new Form1();
popup.Show(this);
e.PpDisp = popup.Browser.ActiveXInstance;
}
public WebBrowserNewWindow2 Browser
{
get { return webBrowser1; }
}
}
Code:
using System;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace SHDocVw
{
public delegate void WebBrowserNewWindow2EventHandler(object sender, WebBrowserNewWindow2EventArgs e);
public class WebBrowserNewWindow2EventArgs : EventArgs
{
public WebBrowserNewWindow2EventArgs(object ppDisp, bool cancel)
{
PpDisp = ppDisp;
Cancel = cancel;
}
public object PpDisp { get; set; }
public bool Cancel { get; set; }
}
public class WebBrowserNewWindow2 : WebBrowser
{
private AxHost.ConnectionPointCookie _cookie;
private WebBrowser2EventHelper _helper;
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
protected override void CreateSink()
{
base.CreateSink();
_helper = new WebBrowser2EventHelper(this);
_cookie = new AxHost.ConnectionPointCookie(
this.ActiveXInstance, _helper, typeof(DWebBrowserEvents2));
}
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
protected override void DetachSink()
{
if (_cookie != null)
{
_cookie.Disconnect();
_cookie = null;
}
base.DetachSink();
}
public event WebBrowserNewWindow2EventHandler NewWindow2;
private class WebBrowser2EventHelper : StandardOleMarshalObject, DWebBrowserEvents2
{
private readonly WebBrowserNewWindow2 _parent;
public WebBrowser2EventHelper(WebBrowserNewWindow2 parent)
{
_parent = parent;
}
public void NewWindow2(ref object pDisp, ref bool cancel)
{
WebBrowserNewWindow2EventArgs arg = new WebBrowserNewWindow2EventArgs(pDisp, cancel);
_parent.NewWindow2(this, arg);
if (pDisp != arg.PpDisp)
pDisp = arg.PpDisp;
if (cancel != arg.Cancel)
cancel = arg.Cancel;
}
}
[ComImport, Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
TypeLibType(TypeLibTypeFlags.FHidden)]
public interface DWebBrowserEvents2
{
[DispId(0xfb)]
void NewWindow2(
[In, Out, MarshalAs(UnmanagedType.IDispatch)] ref object ppDisp,
[In, Out] ref bool cancel);
}
}
}
I know the question is very old but I solved it this way: add new reference, in COM choose Microsoft Internet Controls and in the code, before the click that opens a new window add the following:
SHDocVw.WebBrowser_V1 axBrowser = (SHDocVw.WebBrowser_V1)webBrowser1.ActiveXInstance;
axBrowser.NewWindow += axBrowser_NewWindow;
and then add the following method:
void axBrowser_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed)
{
Processed = true;
webBrowser1.Navigate(URL);
}
My project in using cefsharp winform browser
There are not properly working OnLoadingStateChanged event
after opening some website this event 2 or 3 times trigger
I have no idea how to use properly code for hole website properly loaded then i get event
i am using VS 2015 Community
package version of cefsharp
all packages installed screenshot image
project dot net framework is 4.6.2
This is code i am using
public partial class BrowserWin : UserControl
{
public ChromiumWebBrowser browser;
public bool IsLoading;
public BrowserWin() {
InitializeComponent();
CefSharpSettings.LegacyJavascriptBindingEnabled = true;
browser = new ChromiumWebBrowser();
browser.Dock = DockStyle.Fill;
this.Controls.Add(browser);
//Wait for the page to finish loading
browser.LoadingStateChanged += OnLoadingStateChanged;
browser.FrameLoadStart += Browser_FrameLoadStart;
browser.FrameLoadEnd += Browser_FrameLoadEnd;
}
private void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs args)
{
if (args.IsLoading == false)
{
IsLoading = false;
}
}
private void Browser_FrameLoadStart(object sender, FrameLoadStartEventArgs e)
{
IsLoading = true;
}
private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
}
}
I have problem with awesomium web control 1.7.4 in WPF , when the user click links in page , awesomium navigate to targetURL , but i want to open that links in system default browser.
also I want to determine mailto:jondue#example.com to open this links in default Email client.
Please help me.
Thanks
Update :
I've been doing some more searching to solve my problem, after few days I founded that when the link has a target=_blank the event ShowCreatedWebView is fired. The main problem was about links without target=_blank. After that I'm able to find links without that cause firing event RequestBringIntoView.
private void Browser_ShowCreatedWebView(object sender, Awesomium.Core.ShowCreatedWebViewEventArgs e)
{
System.Diagnostics.Process.Start(Browser.TargetURL.AbsoluteUri);
}
and
private void Browser_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
{
if (Browser.TargetURL != new Uri("about:blank"))
{
System.Diagnostics.Process.Start(Browser.TargetURL.AbsoluteUri);
e.Handled = true;
}
}
I've been doing some more searching to solve my problem, after few days I founded that when the link has a target=_blank the event ShowCreatedWebView is fired. The main problem was about links without target=_blank. After that I'm able to find links without that cause firing event RequestBringIntoView.
private void Browser_ShowCreatedWebView(object sender, Awesomium.Core.ShowCreatedWebViewEventArgs e)
{
System.Diagnostics.Process.Start(Browser.TargetURL.AbsoluteUri);
}
and
private void Browser_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
{
if (Browser.TargetURL != new Uri("about:blank"))
{
System.Diagnostics.Process.Start(Browser.TargetURL.AbsoluteUri);
e.Handled = true;
}
}
You could try using IResourceInterceptor to decide what you want to do when Awesomium loads a page.
public partial class MainWindow : Window
{
public MainWindow()
{
WebCore.Initialize(new WebConfig());
WebCore.Initialized += ((object sender, CoreStartEventArgs e) =>
{
WebCore.ResourceInterceptor = new ResourceInterceptor("http://google.com/");
});
InitializeComponent();
}
}
public class ResourceInterceptor : IResourceInterceptor
{
//Url of the first page to be loaded inside webcontrol without redirection.
protected string m_startupURL;
public ResourceInterceptor(string startupURL)
{
m_startupURL = startupURL;
}
public virtual bool OnFilterNavigation(NavigationRequest request)
{
if (request.Url.ToString() != m_startupURL)
{
System.Diagnostics.Process.Start(request.Url.ToString());
return true;
}
return false;
}
public ResourceResponse OnRequest(ResourceRequest request)
{
return ResourceResponse.Create(request.Url.OriginalString);
}
}
This is a very basic implementation. You should add some additional tests on the Url. Actually Process.Start(request.Url.ToString()) can do anything (launching an application or formatting your disk). So don't forget to test whether it is a valid Url or a mailto: link.
I have some problem with my code. I have silverlight button after I press button I want to load document library and get information about how many items are in this library co my code is:
var web = context.Web;
List sharedDocumentsList = context.Web.Lists.GetByTitle("dokumenty");
int i = sharedDocumentsList.ItemCount;
context.Load(sharedDocumentsList);
context.ExecuteQueryAsync(OnFileWriteSucceeded, OnFileWriteFailed);
But I got still same problem.
The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explixitly requested
How Can I get ItemCount. This is only a simple example I need to work with this list in cycle and so on. But I need to solve this main problem. How to work with this documentlist directly in button click method.
Thank You.
This works for me:
private List docList;
private void GetList()
{
var context = new ClientContext(ApplicationContext.Current.Url);
context.Load(context.Web);
docList = context.Web.Lists.GetByTitle("dokumenty");
context.Load(docList);
context.ExecuteQueryAsync(GetListSucceded, GetListFailed);
}
private void GetListFailed(object sender, ClientRequestFailedEventArgs e)
{
Dispatcher.BeginInvoke(() => MyErrorFunction();
}
private void GetListSucceded(object sender, ClientRequestSucceededEventArgs e)
{
Dispatcher.BeginInvoke(() => GetItemsCount());
}
private void GetItemsCount()
{
MessageBox.Show(docList.ItemCount.ToString());
}