用途:封装只能访问自己的web应用
解决问题:
1、弹出窗口不会跳出,解决了出现IE浏览器的问题
2、获得访问界面的Title作为浏览器的Title
原代码下载地址:http://download.csdn.net/detail/jsyhello/3642313
一、封装WebBrowser(源自互联网网友提供的代码,已不知出处,非常感谢)
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace MyQuery.MyBrower
{
[ComVisible(true)]
public class ExWebBrowser : System.Windows.Forms.WebBrowser
{
private SHDocVw.IWebBrowser2 Iwb2;
protected override void AttachInterfaces(object nativeActiveXObject)
{
Iwb2 = (SHDocVw.IWebBrowser2)nativeActiveXObject;
Iwb2.Silent = true;
base.AttachInterfaces(nativeActiveXObject);
}
protected override void DetachInterfaces()
{
Iwb2 = null;
base.DetachInterfaces();
}
System.Windows.Forms.AxHost.ConnectionPointCookie cookie;
WebBrowserExtendedEvents events;
//This method will be called to give you a chance to create your own event sink
protected override void CreateSink()
{
//MAKE SURE TO CALL THE BASE or the normal events won't fire
base.CreateSink();
events = new WebBrowserExtendedEvents(this);
cookie = new System.Windows.Forms.AxHost.ConnectionPointCookie(this.ActiveXInstance, events, typeof(DWebBrowserEvents2));
}
protected override void DetachSink()
{
if (null != cookie)
{
cookie.Disconnect();
cookie = null;
}
base.DetachSink();
}
//This new event will fire when the page is navigating
public event EventHandler BeforeNavigate;
/// <summary>
/// 可用于替代原来的NewWindow事件,新增了事件的Url参数支持。
/// </summary>
[CategoryAttribute("操作"), DescriptionAttribute("经过扩展的NewWindow事件,使用继承后的WebBrowserExtendedNavigatingEventArgs类型参数实现Url参数支持")]
public event EventHandler BeforeNewWindow;
protected void OnBeforeNewWindow(string url, out bool cancel)
{
EventHandler h = BeforeNewWindow;
WebBrowserExtendedNavigatingEventArgs args = new WebBrowserExtendedNavigatingEventArgs(url, null);
if (null != h)
{
h(this, args);
}
cancel = args.Cancel;
}
protected void OnBeforeNavigate(string url, string frame, out bool cancel)
{
EventHandler h = BeforeNavigate;
WebBrowserExtendedNavigatingEventArgs args = new WebBrowserExtendedNavigatingEventArgs(url, frame);
if (null != h)
{
h(this, args);
}
//Pass the cancellation chosen back out to the events
cancel = args.Cancel;
}
//This class will capture events from the WebBrowser
class WebBrowserExtendedEvents : System.Runtime.InteropServices.StandardOleMarshalObject, DWebBrowserEvents2
{
ExWebBrowser _Browser;
public WebBrowserExtendedEvents(ExWebBrowser browser) { _Browser = browser; }
//Implement whichever events you wish
public void BeforeNavigate2(object pDisp, ref object URL, ref object flags, ref object targetFrameName, ref object postData, ref object headers, ref bool cancel)
{
_Browser.OnBeforeNavigate((string)URL, (string)targetFrameName, out cancel);
}
public void NewWindow3(object pDisp, ref bool cancel, ref object flags, ref object URLContext, ref object URL)
{
_Browser.OnBeforeNewWindow((string)URL, out cancel);
}
}
[System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D"),
System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIDispatch),
System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)]
public interface DWebBrowserEvents2
{
[System.Runtime.InteropServices.DispId(250)]
void BeforeNavigate2(
[System.Runtime.InteropServices.In,
System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.IDispatch)] object pDisp,
[System.Runtime.InteropServices.In] ref object URL,
[System.Runtime.InteropServices.In] ref object flags,
[System.Runtime.InteropServices.In] ref object targetFrameName, [System.Runtime.InteropServices.In] ref object postData,
[System.Runtime.InteropServices.In] ref object headers,
[System.Runtime.InteropServices.In,
System.Runtime.InteropServices.Out] ref bool cancel);
[System.Runtime.InteropServices.DispId(273)]
void NewWindow3(
[System.Runtime.InteropServices.In,
System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.IDispatch)] object pDisp,
[System.Runtime.InteropServices.In, System.Runtime.InteropServices.Out] ref bool cancel,
[System.Runtime.InteropServices.In] ref object flags,
[System.Runtime.InteropServices.In] ref object URLContext,
[System.Runtime.InteropServices.In] ref object URL);
}
}
public class WebBrowserExtendedNavigatingEventArgs : CancelEventArgs
{
private string _Url;
public string Url
{
get { return _Url; }
}
private string _Frame;
public string Frame
{
get { return _Frame; }
}
public WebBrowserExtendedNavigatingEventArgs(string url, string frame)
: base()
{
_Url = url;
_Frame = frame;
}
}
}
二、自己定义的窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using MyQuery.MyBrower;
using System.IO;
using System.Net;
using System.Diagnostics;
namespace MyQuery.MyIE
{
public partial class frmBrower : Form
{
private string url = "http://www.baidu.com";
private bool isError = false;
public frmBrower()
{
InitializeComponent();
}
private void frmBrower_Load(object sender, EventArgs e)
{
this.Text = "加载中......";
try
{
toolStripProgressBar1.Visible = true;
//把自己的网址加入本地安全域中
RegistryKey reg = Registry.CurrentUser;
RegistryKey regSet = reg.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\ZoneMap\\Domains", true);
int p = url .IndexOf("://");
string ip = url.Substring(p + 3);
string http = url.Substring(0, p);
RegistryKey regSetUrl = regSet.OpenSubKey(ip);
if (regSetUrl == null)
{
regSetUrl = regSet.CreateSubKey(ip);
regSetUrl.SetValue(http, 1, RegistryValueKind.DWord);
}
regSetUrl.Close();
regSet.Close();
reg.Close();
this.Enabled = false;
exWebBrowser1.AllowWebBrowserDrop = false;
exWebBrowser1.WebBrowserShortcutsEnabled = false;
exWebBrowser1.ScriptErrorsSuppressed = false;
exWebBrowser1.Navigate(url);
exWebBrowser1.IsWebBrowserContextMenuEnabled = false;
exWebBrowser1.NewWindow += new CancelEventHandler(exWebBrowser1_NewWindow);
((SHDocVw.DWebBrowserEvents_Event)exWebBrowser1.ActiveXInstance).NewWindow += BrowserNewWindow;
exWebBrowser1.BeforeNewWindow += new EventHandler(exWebBrowser1_BeforeNewWindow);
exWebBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(exWebBrowser1_DocumentCompleted);
exWebBrowser1.ProgressChanged += new WebBrowserProgressChangedEventHandler(exWebBrowser1_ProgressChanged);
while (exWebBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
toolStripProgressBar1.Visible = false;
string title = exWebBrowser1.Document.Title;
if (title.IndexOf("无法找到资源") == 0 || title.IndexOf("导航已取消") == 0
|| title.IndexOf("404") == 0 || title.IndexOf("编译错误") == 0
|| title.IndexOf("错误提示") == 0)
{
MessageBox.Show("连接服务器失败,请检查网络是否正常", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
isError = true;
this.Close();
}
else
{
this.Enabled = true;
this.Text = title;
isError = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
isError = true;
this.Close();
}
}
void exWebBrowser1_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
Application.DoEvents();
if ((e.CurrentProgress > 0) && (e.MaximumProgress > 0))
{
toolStripProgressBar1.Visible = true;
}
else if (exWebBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
toolStripProgressBar1.Visible = false;
}
}
void exWebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (exWebBrowser1.ReadyState > WebBrowserReadyState.Interactive)
{
foreach (HtmlElement f in exWebBrowser1.Document.Links)
{
string s = f.GetAttribute("target");
if (s != null && s.ToLower() == "_blank") f.SetAttribute("target", "_self");
}
this.Text = exWebBrowser1.Document.Title;
toolStripProgressBar1.Visible = false;
}
}
void exWebBrowser1_BeforeNewWindow(object sender, EventArgs e)
{
WebBrowserExtendedNavigatingEventArgs eventArgs = e as WebBrowserExtendedNavigatingEventArgs;
if (eventArgs.Url.ToLower() != "about:blank")
{
exWebBrowser1.Navigate(eventArgs.Url);
}
eventArgs.Cancel = true;
}
void Window_Error(object sender, HtmlElementErrorEventArgs e)
{
e.Handled = true;
}
void exWebBrowser1_NewWindow(object sender, CancelEventArgs e)
{
e.Cancel = true;
}
void BrowserNewWindow(string url, int flag, string target, ref object data,
string header, ref bool processed)
{
processed = true;
exWebBrowser1.Navigate(url, null, (byte[])data, header);
}
private void frmBrower_FormClosed(object sender, FormClosedEventArgs e)
{
exWebBrowser1.Dispose();
GC.WaitForPendingFinalizers();
GC.Collect();
}
private void frmBrower_FormClosing(object sender, FormClosingEventArgs e)
{
this.Enabled = false;
}
}
}
欢迎访问:http://121.18.78.216 适易查询分析、工作流、内容管理及项目管理演示平台