webbrowser 响应关闭事件
void registerEvents(System.Windows.Forms.WebBrowser web) { var rnd = new Random(); var head = web.Document.GetElementsByTagName("head")[0]; if (head == null) return; var script = web.Document.CreateElement("script"); IHTMLScriptElement domScript = (IHTMLScriptElement)script.DomElement; domScript.text = @"function registerEvents() { window.ID = '" + web.Name + @"'; }"; head.AppendChild(script); web.Document.InvokeScript("registerEvents"); dynamic win = web.Document.Window.DomWindow as IHTMLWindow2; var id = win.ID as string; if (!dicTabs.ContainsKey(id)) { if (web.Tag != null) dicTabs.Add(id, web.Tag as TabPage); } else if (web.Tag != null) { dicTabs[id] = web.Tag as TabPage; } var ids = tabBrowsers.TabPages.Cast<TabPage>() .Where(page => page.Tag != null).ToList() .Select(page => (page.Tag as WebBrowser).Name).ToList(); var keys = dicTabs.Keys.Where(item => !ids.Contains(item)).ToList(); foreach (var key in keys) dicTabs.Remove(key); } void Window_Unload(object sender, HtmlElementEventArgs e) { var window = sender as HtmlWindow; if (window == null) return; dynamic win = window.DomWindow; if (win != null && win.ID != null) { var id = win.ID as string; var tabPage = tabBrowsers.TabPages.Cast<TabPage>() .Where(page => page.Tag != null && (page.Tag as WebBrowser).Name == id).FirstOrDefault(); if ((tabPage.Tag as WebBrowser).Document != null) return; if (dicTabs.ContainsKey(id)) { this.tabBrowsers.TabPages.Remove(dicTabs[id]); } } }
在Navigated事件中注册:
registerEvents(web); web.Document.Window.Unload += new HtmlElementEventHandler(Window_Unload);
桂棹兮兰桨,击空明兮溯流光。