WPF的WebBrowser屏蔽弹出脚本错误窗体
2017-07-03 08:30 tlnshuju 阅读(592) 评论(0) 编辑 收藏 举报WPF自带的WebBrowser在訪问一些有问题的网页时常常跳出非常多提示脚本错误的窗体, 可是WPF没有自带屏蔽这些窗体的方法或属性.
所以网上找来一使用反射的方法来屏蔽弹出脚本错误窗体的方法, 非常管用.
代码例如以下:
public void SuppressScriptErrors(WebBrowser wb, bool Hide)
{
FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
if (fiComWebBrowser == null) return;
object objComWebBrowser = fiComWebBrowser.GetValue(wb);
if (objComWebBrowser == null) return;
objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { Hide });
}
void webBrowser1_Navigated(object sender, NavigationEventArgs e)
{
SuppressScriptErrors(webBrowser1, true);
}
{
FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
if (fiComWebBrowser == null) return;
object objComWebBrowser = fiComWebBrowser.GetValue(wb);
if (objComWebBrowser == null) return;
objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { Hide });
}
void webBrowser1_Navigated(object sender, NavigationEventArgs e)
{
SuppressScriptErrors(webBrowser1, true);
}
也能够做成扩展方法, 这样比較好调用.
public static class WebBrowserExtensions
{
public static void SuppressScriptErrors(this WebBrowser webBrowser, bool hide)
{
FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
if (fiComWebBrowser == null) return;
object objComWebBrowser = fiComWebBrowser.GetValue(webBrowser);
if (objComWebBrowser == null) return;
objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { hide });
}
}
{
public static void SuppressScriptErrors(this WebBrowser webBrowser, bool hide)
{
FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
if (fiComWebBrowser == null) return;
object objComWebBrowser = fiComWebBrowser.GetValue(webBrowser);
if (objComWebBrowser == null) return;
objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { hide });
}
}
仅仅需在显示网页前调用下面语句就可以:
this.myWebBrower.SuppressScriptErrors(true);
本文来自今路客的博客,原文地址:http://blog.jinlook.com/archives/96.html