Can I detect errors while using a .Net WebBrowser control?

折月煮酒 提交于 2019-12-20 18:29:27

问题


I have an .Net Froms application that displays web pages through a WebBrowser control.

Is there anyway that I can detect if the control shows a 'Page not found' or 'Cannot display webpage' error? There doesn't seem to be any error event handlers.


回答1:


The WebBrowser windows forms control is wrapper around Internet Explorer and it doesn't expose all the functionality of the underlying ActiveX control and particularly the NavigateError event. Here's a workaround:

First add reference to SHDocVw.dll to your project (COM tab of Add Reference window). Then you can do the following to capture errors:

private void button1_Click(object sender, EventArgs e)
{
    SHDocVw.WebBrowser instance = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance;
    instance.NavigateError += new SHDocVw.DWebBrowserEvents2_NavigateErrorEventHandler(instance_NavigateError);
    webBrowser1.Navigate("http://www.google.com/foo");
}

void instance_NavigateError(object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel)
{
    // Do whatever you want with the error            
}



回答2:


I found another way to solve this without setting a reference to the SHDocVw dll.

See web browser CreateSink method on MSDN.



来源:https://stackoverflow.com/questions/368612/can-i-detect-errors-while-using-a-net-webbrowser-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!