WebBrowser с вкладками на C#

WebBrowser с вкладками на C#

Основные характеристики:
1) Создание компонента webBrowser происходит динамически.
2) Компонент имеет вкладки, которые можно добавлять и удалять.
3) Есть возможность навигации через textBox
4) Возможен переход по ссылке javascript ссылке с последующем открытием новой вкладки.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;
namespace WindowsFormsApplication82
{
    public partial class Form1 : Form
    {
        TabControl TabControl1 = new TabControl();
        WebBrowserEx WebBrowser1;
        TabPage TabPage1;
        int i = 0;
        public Form1()
        {
            InitializeComponent();
        }
        public class WebBrowserEx : WebBrowser
        {
            #region NewWindow2
            private AxHost.ConnectionPointCookie cookie;
            private WebBrowser2EventHelper helper;
            [DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
            [DispIdAttribute(200)]
            public object Application
            {
                get
                {
                    if (this.ActiveXInstance == null)
                    {
                        throw new AxHost.InvalidActiveXStateException("Application", AxHost.ActiveXInvokeKind.PropertyGet);
                    }
                    return (this.ActiveXInstance as IWebBrowser2).Application;
                }
            }
            [DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
            [DispIdAttribute(552)]
            public bool RegisterAsBrowser
            {
                get
                {
                    if (this.ActiveXInstance == null)
                    {
                        throw new AxHost.InvalidActiveXStateException("RegisterAsBrowser", AxHost.ActiveXInvokeKind.PropertyGet);
                    }
                    return (this.ActiveXInstance as IWebBrowser2).RegisterAsBrowser;
                }
                set
                {
                    if (this.ActiveXInstance == null)
                    {
                        throw new AxHost.InvalidActiveXStateException("RegisterAsBrowser", AxHost.ActiveXInvokeKind.PropertyGet);
                    }
                    (this.ActiveXInstance as IWebBrowser2).RegisterAsBrowser = value;
                }
            }
            [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
            protected override void CreateSink()
            {
                base.CreateSink();
                helper = new WebBrowser2EventHelper(this);
                cookie = new AxHost.ConnectionPointCookie(this.ActiveXInstance, helper, typeof(DWebBrowserEvents2));
            }
            [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
            protected override void DetachSink()
            {
                if (cookie != null)
                {
                    cookie.Disconnect();
                    cookie = null;
                }
                base.DetachSink();
            }
            public event WebBrowserNewWindow2EventHandler NewWindow2 = (o, e) => { };
            protected virtual void OnNewWindow2(WebBrowserNewWindow2EventArgs e)
            {
                NewWindow2(this, e);
            }
            private class WebBrowser2EventHelper : StandardOleMarshalObject, DWebBrowserEvents2
            {
                private WebBrowserEx parent;
                public WebBrowser2EventHelper(WebBrowserEx parent)
                {
                    this.parent = parent;
                }
                public void NewWindow2(ref object ppDisp, ref bool cancel)
                {
                    var e = new WebBrowserNewWindow2EventArgs(ppDisp);
                    this.parent.OnNewWindow2(e);
                    ppDisp = e.ppDisp;
                    cancel = e.Cancel;
                }
            }
            #endregion
        }
        public delegate void WebBrowserNewWindow2EventHandler(object sender, WebBrowserNewWindow2EventArgs e);
        public class WebBrowserNewWindow2EventArgs : CancelEventArgs
        {
            public object ppDisp { get; set; }
            public WebBrowserNewWindow2EventArgs(object ppDisp)
            {
                this.ppDisp = ppDisp;
            }
        }
        [ComImport, Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D")]
        [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
        [TypeLibType(TypeLibTypeFlags.FHidden)]
        public interface DWebBrowserEvents2
        {
            [DispId(251)]
            void NewWindow2(
            [InAttribute(), OutAttribute(), MarshalAs(UnmanagedType.IDispatch)] ref object ppDisp,
            [InAttribute(), OutAttribute()] ref bool cancel);
        }
        [ComImport, Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E")]
        [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
        public interface IWebBrowser2
        {
            object Application { get; }
            bool RegisterAsBrowser { get; set; }
        }
        private void webBrowserEx1_NewWindow2(object sender, WebBrowserNewWindow2EventArgs e)
        {
            this.WebBrowser1 = new WebBrowserEx();
            this.WebBrowser1.Dock = DockStyle.Fill;
            WebBrowser1.NewWindow2 += webBrowserEx1_NewWindow2;
       
            this.TabPage1 = new TabPage();
            this.TabPage1.Controls.Add(WebBrowser1);
            
            this.TabControl1.Controls.Add(TabPage1);
            this.TabControl1.SelectedTab = TabPage1;
            e.ppDisp = this.WebBrowser1.Application;
            this.WebBrowser1.RegisterAsBrowser = true;
            WebBrowser1.DocumentCompleted += web_DocumentComplited;
            WebBrowser1.ScriptErrorsSuppressed = true;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.WebBrowser1 = new WebBrowserEx();
            this.WebBrowser1.Dock = DockStyle.Fill;
            WebBrowser1.NewWindow2 += webBrowserEx1_NewWindow2;
          
            this.TabPage1 = new TabPage();
            this.TabPage1.Controls.Add(WebBrowser1);
           
            this.TabControl1.Location = new Point(TabControl1.Location.X + 10, TabControl1.Location.Y + 30);
            this.TabControl1.Dock = DockStyle.None;
            this.TabControl1.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
            this.TabControl1.Width = this.Width - 30;
            this.TabControl1.Height = this.Height - 30;
            this.TabControl1.TabPages.Add(TabPage1);
            this.TabControl1.SelectTab(i);
            this.TabControl1.SelectedTab.Controls.Add(this.WebBrowser1);
            this.Controls.Add(this.TabControl1);
            WebBrowser1.DocumentCompleted += web_DocumentComplited;
            WebBrowser1.ScriptErrorsSuppressed = true;
            this.WebBrowser1.Navigate("https://www.yandex.ru");
            i += 1;
        }
        void web_DocumentComplited(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            this.TabControl1.SelectedTab.Text = ((WebBrowser)this.TabControl1.SelectedTab.Controls[0]).DocumentTitle;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.WebBrowser1 = new WebBrowserEx();
            this.WebBrowser1.Dock = DockStyle.Fill;
            WebBrowser1.NewWindow2 += webBrowserEx1_NewWindow2;
         
            this.TabPage1 = new TabPage();
            this.TabPage1.Controls.Add(WebBrowser1);
            
            this.TabControl1.TabPages.Add(TabPage1);
            this.Controls.Add(this.TabControl1);
            this.TabControl1.SelectTab(TabPage1);
            this.TabControl1.SelectedTab.Text = "Это новая вкладка";
            WebBrowser1.ScriptErrorsSuppressed = true;
            WebBrowser1.DocumentCompleted += web_DocumentComplited;
            //
            this.TabControl1.Text = this.WebBrowser1.DocumentTitle;
            i += 1;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (this.TabControl1.TabPages.Count - 1 > 0)
            {
                this.TabControl1.TabPages.RemoveAt(this.TabControl1.SelectedIndex);
                this.TabControl1.SelectTab(this.TabControl1.TabPages.Count - 1);
                i -= 1;
            }
        }
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true;
                ((WebBrowser)this.TabControl1.SelectedTab.Controls[0]).Navigate(textBox1.Text);
            }
        }
    }
}

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *