C#打开浏览器。关闭浏览器

-----------------------------------------

  /// <summary>
    /// 调用前端的静态页面的类 (调用ie的内核)
    /// </summary>
    public class FinalHtml
    {
        private String htmlString;
        private String url;
        private String htmlTitle;
        // 获得html title标签的内容
        public String HtmlTitle
        {
            get
            {
                if (success == false) return null;
                return htmlTitle;
            }
        }
        private List<string> linkList;
        private List<string> imageList;
        private bool success; // 是否成功运行
        ///
        /// 获得网页所有链接的链表, 一定要在Run之后进行
        ///
        public List<string> LinkList
        {
            get
            {
                if (success == false) return null;
                return linkList;
            }
        }
        ///
        /// 获得所有图像的标签, 一定要在Run之后进行
        ///
        public List<string> ImageList
        {
            get
            {
                if (success == false) return null;
                return imageList;
            }
        }
        ///
        /// 获得执行完js之后的网页body 部分的html代码
        ///
        public String HtmlBody
        {
            get
            {
                if (success == false) return null;
                return htmlString;
            }
        }
        public FinalHtml()
        {
            linkList = new List<string>();
            imageList = new List<string>();
            htmlString = "";
            success = false;
        }
        ///
        /// 检查并补充设置url
        ///
        ///
        private void CheckURL(String url)
        {
            if (!url.StartsWith("http://") && !url.StartsWith("https://") && !url.StartsWith("file:///"))
                url = "http://" + url;
            this.url = url;
        }
        ///
        /// 加载指定文件
        ///
        /// 文件URL
        /// 超时时限
        /// 是否成功运行,没有超时
        public bool Run(String url, int timeOut = 10000)
        {
            CheckURL(url);
            Thread newThread = new Thread(NewThread);
            newThread.SetApartmentState(ApartmentState.STA);/// 为了创建WebBrowser类的实例 必须将对应线程设为单线程单元
            newThread.Start();
            //监督子线程运行时间
            while (newThread.IsAlive && timeOut > 0)
            {
                Thread.Sleep(100);
                timeOut -= 100;
            }
            // 超时处理
            if (newThread.IsAlive)
            {
                if (success) return true;
                newThread.Abort();
                return false;
            }
            return true;
        }

        private void NewThread()
        {
            new FinalHtmlPerThread(this);
            Application.Run();// 循环等待webBrowser 加载完毕 调用 DocumentCompleted 事件
        }
        ///
        ///  用于处理一个url的核心类
        ///
        class FinalHtmlPerThread : IDisposable
        {
            FinalHtml master;
            WebBrowser web;

            public FinalHtmlPerThread(FinalHtml master)
            {
                this.master = master;
                DealWithUrl();
            }
            private void DealWithUrl()
            {
                String url = master.url;
                web = new WebBrowser();
                bool success = false;
                try
                {
                    web.Url = new Uri(url);
                    web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted); // 对事件加委托
                    success = true;
                }
                finally
                {
                    if (!success)
                        Dispose();
                }

            }
            public void Dispose()
            {
                if (!web.IsDisposed)
                    web.Dispose();
            }
            private void ToList(HtmlElementCollection collection, List<string> list)
            {
                System.Collections.IEnumerator it = collection.GetEnumerator();
                while (it.MoveNext())
                {
                    HtmlElement htmlElement = (HtmlElement)it.Current;
                    list.Add(htmlElement.OuterHtml);
                }
            }
            private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
            {
                //微软官方回答一个网页有多个Ifram元素就有可能触发多次此事件, 并且提到了
                // vb 和 C++ 的解决方案, C# 没有提及,经本人尝试,发现下面的语句可以判断成功
                // 如果未完全加载 web.ReadyState = WebBrowserReadyState.Interactive
                if (web.ReadyState != WebBrowserReadyState.Complete) return;
                master.htmlTitle = web.Document.Title;
                ToList(web.Document.Links, master.linkList);
                ToList(web.Document.Images, master.imageList);
                master.htmlString = web.Document.Body.InnerHtml;
                master.success = true;
                Thread.CurrentThread.Abort();
            }
        }
    }

-----------调用---------------

            //用IE执行运行相应的连接
            StringBuilder sb = new StringBuilder();
            try
            {

                FinalHtml html = new FinalHtml();

      //打开的连接。
                if (html.Run("http://192.168.0.145:8080/webPhone/test_canvas/1.html"))
                {

                }

            }
            catch (Exception ex)
            {

                throw;
            }

------------------------------------

     var d = Process.Start(@"D:\安装软件\Mozilla Firefox\firefox.exe", "http://192.168.0.145:8080/webPhone/test_canvas/1.html");//本地的火狐浏览器



---------------------------------------关闭进程----
                foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("firefox"))
                {
                    p.Kill();
                }

posted @ 2017-01-19 09:46  游林  阅读(2883)  评论(0编辑  收藏  举报