MouStudio分享 http://blog.sciencenet.cn/u/moustudio 一目半行,再目半行

博文

C#开发多功能语言复读机 ---之--- 网页浏览器开发

已有 6918 次阅读 2009-11-6 14:23 |个人分类:编程笔记|系统分类:科研笔记| 网页浏览器, WebBrowser

Captain Dialog 2009-11-06

 
1 基本的网页浏览器功能   

    利用C#开发网页浏览器需要用到WebBrowser控件,使用方法可以参考:Creating a simple web broswer http://www.dreamincode.net/forums/showtopic57191.htm, 的确实很简单, 下面介绍一下本项目需要使用的方法过程:

    首先在窗体上添加控件WebBrowser,默认名为WebBrowser1.然后再添加一个工具栏,用于控制网页浏览器的操作。  

   

 //=====================================================================
        #region "Web Broswer操作"

1.1 返回操作,调用方法GoBack();
        private void toolStripButton_Back_Click(object sender, EventArgs e)
        {
            webBrowser1.GoBack();
        }

1.2 前进操作; 

       private void toolStripButton_Forward_Click(object sender, EventArgs e)
        {
            webBrowser1.GoForward();
        }

1.3 刷新操作;

        private void toolStripButton_Refresh_Click(object sender, EventArgs e)
        {
            webBrowser1.Refresh();
        }

1.4 停止操作;

        private void toolStripButton_Stop_Click(object sender, EventArgs e)
        {
            webBrowser1.Stop();
        }

1.5 链接到主页;

        private void toolStripButton_Home_Click(object sender, EventArgs e)
        {
            webBrowser1.GoHome();
        }

1.6 链接到指定的网址;其中地址为oolStripTextBox的输入内容。

        private void toolStripButton_Go_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate(toolStripTextBox_URL.Text);
        }

        增加相应键盘回车响应功能。

        private void toolStripTextBox_URL_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //触发Go按钮单击事件
                webBrowser1.Navigate(toolStripTextBox_URL.Text);
            }
        }

1.7 相应的文档处理;增加了错误指令的控制;防止新窗口打开调用默认的浏览器,而是在本窗口直接打开。

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            toolStripTextBox_URL.Text = e.Url.ToString();

            //重新定向新连接为本窗口--------------------------
            //将所有的链接的目标,指向本窗体
            foreach (HtmlElement archor in this.webBrowser1.Document.Links) {
                archor.SetAttribute("target", "_self");
            }

            //将所有的FORM的提交目标,指向本窗体
            foreach (HtmlElement form in this.webBrowser1.Document.Forms) {
                form.SetAttribute("target", "_self");
            }

        }

        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            Status.Text = e.Url.ToString();

            this.Text = e.Url + " - Web Browser";
            ProgressBarStatus.Visible = false;
        }

        private void webBrowser1_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
        {
            ProgressBarStatus.Maximum = Convert.ToInt32(e.MaximumProgress);
            ProgressBarStatus.Value = Convert.ToInt32(e.CurrentProgress);
        }

        private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            ProgressBarStatus.Visible = true;
        }

        //禁用新窗口打开
        private void webBrowser1_NewWindow(object sender, CancelEventArgs e) {
            e.Cancel = true;
        }

Appendix:由于基本的WebBrowser操作可能会在网页浏览过程中出现各种问题,所以进行了一些列的修正方法,查阅了大量的文献之后,参考了一下的一些方法:

[1] C#防止WebBrowser在新窗口中打开链接页面 http://www.zu14.cn/2009/07/31/csharp-webbrowser-avoid-to-open-link-in-new-window/ ;

[2] WebBrowser控件禁用超链接转向、脚本错误提示、默认右键菜单和快捷键 http://www.zu14.cn/2008/11/19/webbrowser/ ;

2 网页浏览器加强功能

2.1 保存网页文件

2.1.1将网页保存为Mht文件,参考 http://luoyahu.javaeye.com/blog/397159 方法后:

        private void toolStripButton_Save_Click(object sender, EventArgs e)
        {
            using(SaveFileDialog save = new SaveFileDialog())
            {
                save.Filter = "MHT文件|*.mht";
                if (save.ShowDialog() == DialogResult.OK)
                {
                    string str_FilePath = save.FileName;
                    CDO.Message msg = new CDO.MessageClass();
                    CDO.Configuration cfg = new CDO.ConfigurationClass();
                    msg.Configuration = cfg;
                    msg.CreateMHTMLBody(toolStripTextBox_URL.Text, CDO.CdoMHTMLFlags.cdoSuppressAll, "", "");
                    msg.GetStream().SaveToFile(str_FilePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite);

                    // MessageBox.Show("保存成功:" + toolStripTextBox_URL.Text);
                    notifyIcon1.BalloonTipTitle = "信息提示";
                    notifyIcon1.BalloonTipText = String.Format("文件保存成功:rn{0}", toolStripTextBox_URL.Text);
                    notifyIcon1.ShowBalloonTip(1000);
                }               
            }
        }

2.1.2 将网页保存为Http文件;

        private void toolStripButton_Save2HTTP_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog save = new SaveFileDialog()) {
                save.Filter = "HTM文件|*.htm";
                if (save.ShowDialog() == DialogResult.OK) {
                    string str_FilePath = save.FileName;

                    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(toolStripTextBox_URL.Text);
                    HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();

                    StreamReader respStream = new StreamReader(myResp.GetResponseStream(), Encoding.Default);
                    string respStr = respStream.ReadToEnd();
                    respStream.Close();

                    FileStream fs = new FileStream(str_FilePath, FileMode.Create, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                    sw.Write(respStr);
                    sw.Close();

                    // MessageBox.Show("保存成功:" + toolStripTextBox_URL.Text);
                    notifyIcon1.BalloonTipTitle = "信息提示";
                    notifyIcon1.BalloonTipText = String.Format("文件保存成功:rn{0}", toolStripTextBox_URL.Text);
                    notifyIcon1.ShowBalloonTip(1000);
                }
            }

        }

2.1.3 将网页保存为图片;具体方法参考了:C# 网页抓图 实现 SNAP 的效果 http://www.zu14.cn/2009/02/11/csharp-webpage-snapshot/
        private void toolStripButton_Save2Pic_Click(object sender, EventArgs e) {
            try {
                saveFileDialog.InitialDirectory = str_Project+"\"+str_ProjectName;
                saveFileDialog.FileName = str_Project + "\" + str_ProjectName;
                DialogResult result = saveFileDialog.ShowDialog();
                if (result == DialogResult.OK && !string.IsNullOrEmpty(saveFileDialog.FileName)) {
                    string filename = saveFileDialog.FileName.Trim();
                    ImageFormat format = ImageFormat.Jpeg;
                    switch (filename.ToLower()) {
                        case "bmp":
                            format = ImageFormat.Bmp;
                            break;
                        case "jpg":
                        case "jpeg":
                            format = ImageFormat.Jpeg;
                            break;
                        case "png":
                        default:
                            format = ImageFormat.Png;
                            break;

                    }

                    SaveImage(saveFileDialog.FileName, format);
                    if (MessageBox.Show("保存完成!n是否打开图片文件?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) {
                        System.Diagnostics.Process.Start(filename);
                    }
                }
            }
            catch { }
        }

        //保存为图片
        private void SaveImage(string path, ImageFormat format) {
            int browserWidth = webBrowser1.Width;
            int browserHeight = webBrowser1.Height;
            Rectangle rectBody = this.webBrowser1.Document.Body.ScrollRectangle;
            int width = rectBody.Width + 20;
            int height = rectBody.Height;
            this.webBrowser1.Width = width;
            this.webBrowser1.Height = height;
            try {
                SnapLibrary.Snapshot snap = new SnapLibrary.Snapshot();
                using (Bitmap bmp = snap.TakeSnapshot(this.webBrowser1.ActiveXInstance, new Rectangle(0, 0, width, height))) {
                    //this.webBrowser.DrawToBitmap(bmp, new Rectangle(0, 0, width, height));
                    bmp.Save(path, format);
                    //using (Image img = ImageHelper.GetThumbnailImage(bmp, bmp.Width, bmp.Height))
                    //{
                    //    ImageHelper.SaveImage(img, path, format);
                    //}
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            this.webBrowser1.Width = browserWidth;
            this.webBrowser1.Height = browserHeight;
        }

2.2 网页地址自动补全操作

添加一个用于存放地址的ComboBox控件,并且设置一些参数:

        AutoCompletMode = SuggestAppend; AutoCompleteSource = ListItems;

定义内存上用于存储地址的变量:

        //自动补全网址存储
        DataTable dt_WebAddress;

窗体初始化时候设置:

           //网页地址自动补全的相关操作
            dt_WebAddress = new DataTable();
            cbx_WebAddress.DataSource = dt_WebAddress;
            dt_WebAddress.Columns.Add("Name");
            dt_WebAddress.Columns.Add("VV");
            cbx_WebAddress.DisplayMember = "Name";
            cbx_WebAddress.ValueMember = "VV"; 

地址数据保存:

      private void cbx_WebAddress_Leave(object sender, EventArgs e) {
            //增加已经输入的地址
            dt_WebAddress.Rows.Add(new string[] { cbx_WebAddress.Text, "x" });
        }

        //网页地址输入2
        private void cbx_WebAddress_KeyDown(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) {
                //触发Go按钮单击事件
                webBrowser1.Navigate(cbx_WebAddress.Text);
                //增加已经输入的地址
                dt_WebAddress.Rows.Add(new string[] { cbx_WebAddress.Text, "x" });
            }
        }

   #endregion

2.3 收藏夹功能实现

  

窗体初始化:

        //收藏夹
        BuildTopTree(this.treeView);

        //添加链接
        private void btn_AddLink_Click(object sender, EventArgs e) {
            toolStripButton_AddLink_Click(sender, e);
        }

     #region "网页收藏夹操作"
        public void BuildTopTree(TreeView tv)
        {
            TreeNodeCollection tnParentNodes = tv.Nodes;
            TreeNode tnChildNode;
            tnParentNodes.Clear();
            strSQL = "select * from Favorite where parent_id=0";
            DataTable dtTop = AccessDataBase.GetDataTable(strSQL);
            int countTop = dtTop.Rows.Count;
            for (int i = 0; i < countTop; i++)
            {
                tnChildNode = new TreeNode();
                tnChildNode.Tag = dtTop.Rows[i]["id"].ToString();
                tnChildNode.Text = dtTop.Rows[i]["title"].ToString();

                tnChildNode.ContextMenuStrip = contextMenuStrip_Group;
                strSQL = string.Format("select * from Favorite where parent_id={0}", tnChildNode.Tag.ToString());
                DataTable dtSub = AccessDataBase.GetDataTable(strSQL);
                int countSub = dtSub.Rows.Count;

                for (int j = 0; j < countSub; j++)
                {
                    TreeNode tnTempNode = new TreeNode();
                    tnTempNode.Tag = dtSub.Rows[j]["id"].ToString();
                    tnTempNode.Text = dtSub.Rows[j]["title"].ToString();
                    tnTempNode.ToolTipText = dtSub.Rows[j]["description"].ToString();
                    tnTempNode.ContextMenuStrip = contextMenuStrip_Link;
                    tnTempNode.ImageIndex = 2;
                    tnTempNode.SelectedImageIndex = 2;
                    tnChildNode.Nodes.Add(tnTempNode);
                }
                tnParentNodes.Add(tnChildNode);

            }
        }

        private void renameToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            tnTreeNode = treeView.SelectedNode;
            if (tnTreeNode == null)
            {
                MessageBox.Show(this, "请选择相应的链接!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            id = Convert.ToInt32(tnTreeNode.Tag);
            LinkForm form = new LinkForm();
            form.Title = "重命名标题";
            form.LinkTitle = tnTreeNode.Text;
            form.EnableTitle = false;
            DialogResult dr = form.ShowDialog(this);
            if (dr.Equals(DialogResult.OK))
            {

                strSQL = string.Format("update Favorite set title='{0}' where id={1}", form.LinkTitle, id);
                AccessDataBase.ExecuteSql(strSQL);
                BuildTopTree(this.treeView);
            }
        }

        private void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            tnTreeNode = treeView.SelectedNode;
            if (tnTreeNode == null)
            {
                MessageBox.Show(this, "请选择相应的链接!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            id = Convert.ToInt32(tnTreeNode.Tag);
            String strMsg = String.Format("确认要删除'{0}'吗?", tnTreeNode.Text);
            DialogResult dr = MessageBox.Show(this, strMsg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (dr.Equals(DialogResult.OK))
            {
                strSQL = String.Format("delete from Favorite where id={0}", id);
                AccessDataBase.ExecuteSql(strSQL);
                BuildTopTree(this.treeView);
            }
        }

        private void propertyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tnTreeNode = treeView.SelectedNode;
            if (tnTreeNode == null)
            {
                MessageBox.Show(this, "请选择相应的链接!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            id = Convert.ToInt32(tnTreeNode.Tag);
            LinkForm form = new LinkForm();
            form.Title = "链接的属性";

            strSQL = string.Format("select * from Favorite where id={0}", id);
            DataTable dt = AccessDataBase.GetDataTable(strSQL);
            form.LinkTitle = dt.Rows[0]["title"].ToString();
            form.Url = dt.Rows[0]["url"].ToString();
            form.Description = dt.Rows[0]["description"].ToString();
            form.Parnet_Id = Convert.ToInt32(dt.Rows[0]["parent_id"]);
            DialogResult dr = form.ShowDialog(this);
            if (dr.Equals(DialogResult.OK))
            {

 

                strSQL = string.Format("update Favorite set title='{0}',url='{1}',description='{2}',parent_id={3} where id={4}", form.LinkTitle, form.Url, form.Description, form.Parnet_Id, id);
                AccessDataBase.ExecuteSql(strSQL);
                BuildTopTree(this.treeView);
            }
        }

        //重命名组
        private void renameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tnTreeNode = treeView.SelectedNode;
            if (tnTreeNode == null)
            {
                MessageBox.Show(this, "请选择相应的分类!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            id = Convert.ToInt32(tnTreeNode.Tag);
            GroupForm form = new GroupForm();
            form.Title = "重命名分组";
            form.GroupName = tnTreeNode.Text;
            DialogResult dr = form.ShowDialog(this);
            if (dr.Equals(DialogResult.OK))
            {

                strSQL = string.Format("update Favorite set [title]='{0}' where id={1}", form.GroupName, id);
                AccessDataBase.ExecuteSql(strSQL);
                BuildTopTree(this.treeView);
            }
        }

        //删除组
        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tnTreeNode = treeView.SelectedNode;
            if (tnTreeNode == null)
            {
                MessageBox.Show(this, "请选择相应的分类!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            id = Convert.ToInt32(tnTreeNode.Tag);

            strSQL = string.Format("select * from Favorite where parent_id={0}", id);

            int count = 0;
            count = AccessDataBase.GetDataTable(strSQL).Rows.Count;
            if (count != 0)
                MessageBox.Show(this, "请先清空该组下的项!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
            {
                String strMsg = String.Format("确认要删除'{0}'吗?", tnTreeNode.Text);
                DialogResult dr = MessageBox.Show(this, strMsg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (dr.Equals(DialogResult.OK))
                {
                    strSQL = String.Format("delete from Favorite where id={0}", id);
                    AccessDataBase.ExecuteSql(strSQL);
                    BuildTopTree(this.treeView);
                }
            }
        }

        private void toolStripButton_AddLink_Click(object sender, EventArgs e)
        {
            LinkForm form = new LinkForm();
            form.Title = "添加链接";
            form.textBox_Url.Text = toolStripTextBox_URL.Text;

            DialogResult dr = form.ShowDialog(this);
            if (dr.Equals(DialogResult.OK))
            {
                strSQL = String.Format("insert into Favorite(title,url,description,parent_id)values('{0}','{1}','{2}','{3}')", form.LinkTitle, form.Url, form.Description, form.Parnet_Id);
                AccessDataBase.ExecuteSql(strSQL);
                BuildTopTree(this.treeView);
            }
        }

        private void btn_AddNewGroup_Click(object sender, EventArgs e)
        {
            soundSlide.Play();

            GroupForm form = new GroupForm();
            form.Title = "添加分组";
            DialogResult dr = form.ShowDialog(this);
            if (dr.Equals(DialogResult.OK))
            {
                strSQL = String.Format("insert into Favorite(title)values('{0}')", form.GroupName);
                AccessDataBase.ExecuteSql(strSQL);
                BuildTopTree(this.treeView);
            }
        }

        private void treeView_MouseUp(object sender, MouseEventArgs e)
        {
            //当鼠标右击时,将鼠标所在的节点作为选中节点()
            Point p = new Point(e.X, e.Y);
            TreeNode tnTempNode = this.treeView.GetNodeAt(p);
            if (tnTempNode != null && e.Button == MouseButtons.Right)
            {
                this.treeView.SelectedNode = tnTempNode;

            }
            if (tnTempNode != null && e.Button == MouseButtons.Left)
            {
                this.treeView.SelectedNode = tnTempNode;

                if (this.treeView.SelectedNode.Nodes.Count == 0)
                {

                    id = Convert.ToInt32(this.treeView.SelectedNode.Tag);
                    strSQL = string.Format("select url from Favorite where id={0}", id);
                    String url = AccessDataBase.GetDataTable(strSQL).Rows[0]["url"].ToString();

                    //CreateNewWebBrowser().Navigate(url);
                    webBrowser1.Navigate(url);
                }

            }
        }

        #endregion

 

3 讨论

    还有就是现在十分流行的多页浏览的功能,需要动态操作TabPages的实现,暂时没有实现。







https://blog.sciencenet.cn/blog-244606-269045.html

上一篇:C#开发多功能语言复读机 ---之--- 软件使用介绍V1.0
下一篇:C#实现自动登录126邮箱
收藏 IP: .*| 热度|

0

发表评论 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-11-23 00:12

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部