注:本文适用.net 2.0+的winform项目
目的:
上述窗体是指WebBrowser所在的Form,基本上,上述目的就是让该窗体表现得像个正常浏览器而已。
WebBrowser(下称wb)自带NewWindow事件,所以直接注册该事件即可:
private void wb_NewWindow(object sender, CancelEventArgs e)
{
e.Cancel = true;//这句加不加在我的环境里没区别,不加也不会导致打开外部浏览器
new FmWebBrowser(wb.StatusText).Show(); //FmWebBrowser即我的承载wb的窗体,本类构造函数接受一个url,Show之后会令wb访问该url。另外,该事件进入时,wb的StatusText几乎可以断定就是所点链接的href,极端情况以后遇到再说
}
由于wb没有现成的Close之类的事件,所以这个要稍稍折腾一下,就是给它加上这个事件,核心要解决的问题,就是让wb知道页面执行了window.close(),解决了这个,剩下就是把这事通知出去而已。
using System;
using System.Security.Permissions;
using System.Windows.Forms;
namespace AhDung.WinForm.Controls
{
/// <summary>
/// 增强型浏览器
/// </summary>
public class WebBrowserEx : WebBrowser
{
/// <summary>
/// 当WebBrowser关闭后
/// </summary>
public event EventHandler WindowClosed;
protected void OnWindowClosed(EventArgs e)
{
if (WindowClosed != null) { WindowClosed(this, e); }
}
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x210/*WM_PARENTNOTIFY*/)
{
int wp = m.WParam.ToInt32();
int X = wp & 0xFFFF;
if (X == 0x2/*WM_DESTROY*/)//若收到该消息,引发WindowClosed事件
{
OnWindowClosed(EventArgs.Empty);
}
}
base.WndProc(ref m);
}
}
}
private WebBrowserEx wbex = new WebBrowserEx();
...
public FmMain()
{
wbex.WindowClosed += wbex_WindowClosed;
...
}
void wbex_WindowClosed(object sender, System.EventArgs e)
{
this.Close();
}
- 文毕 -
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有