Note: This article is for .net winform project 2.0+
purpose:
- Click on the page target = "_ blank" link to bring up a new window
- When the page includes the window.close (), close the window
Form refers to Form WebBrowser above where, basically, the object is to make the form behave like a normal browser only.
First, the new pop-up window
WebBrowser (hereinafter referred to as wb) comes NewWindow event, so you can directly register for this event:
void wb_NewWindow Private (Object SENDER, CancelEventArgs E) { the e.Cancel = to true; // sentence plus without my environment no difference, it will not lead to open without external browser new FmWebBrowser (wb.StatusText). Show (); // FmWebBrowser that is carrying my wb form, the class constructor accepts a url, then Show will make wb access the url. In addition, when the event is entered, wb of StatusText almost certainly is the point of the link href, after the extreme conditions encountered say }
Second, in response to the page close to the present form window.close
Since no existing events Close wb and the like, so this is slightly tossing about, is to give it with this event, the core problem to be solved is to let know wb page executed window.close (), to solve this, left under that notice these things out of it.
- Let wb pages knows performed window.close (), and trigger specific events
wb receive a copy of the online method, the principle is the page execution window.close () win32 when a particular message, so wb can override the WndProc method to process the message, which requires inherit wb write a subclass, classes are as follows:
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 / * the WM_PARENTNOTIFY * /) { int m.WParam.ToInt32 WP = (); int = X-WP & 0xFFFF; IF (X-== 0x2 / * the WM_DESTROY * /) // If the received the message, event triggered WindowClosed { OnWindowClosed (EventArgs.Empty); } } base.WndProc (REF m); } } }
- The rest is simple, the host response WindowClosed event WebBrowserEx form of close themselves just fine. First, of course WebBrowser should be replaced before the above WebBrowserEx, snippet:
private WebBrowserEx wbex = new WebBrowserEx(); ... public FmMain() { wbex.WindowClosed += wbex_WindowClosed; ... } void wbex_WindowClosed(object sender, System.EventArgs e) { this.Close(); }
-