Google在线翻译(WinForm版)

来源:互联网 发布:c语言编程学校 编辑:程序博客网 时间:2024/05/22 09:57

   最近闲的无事,写了一个Google在线翻译的WinForm版,里面用到了webbrowser空间,本来是不想用这个空间的,但是直接POST提交数据上去,没办法得到返回信息,返回的信息一直为空,很是郁闷,所以不得已用到了webbrowser空间,话不多说,直接上代码.

 


 

 

 

 

 

 

 

 

 

  private void button1_Click(object sender, EventArgs e)
        {
            if (this.textBox1.Text.Equals("") || this.comboBox1.Text.Equals(""))
            {
                MessageBox.Show("请填写内容");
            }
            else
            {
                this.setvalues();
                HtmlElement form = webBrowser1.Document.GetElementById("text_form");
                form.InvokeMember("submit");
                this.textBox2.Text = this.getContent();
            }
        }
        //赋值
        public void setvalues()
        {
            webBrowser1.Document.Forms["text_form"].Document.GetElementById("text").InnerText = this.textBox1.Text;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.comboBox1.Items.Add("从英文到中文");
            this.comboBox1.Items.Add("从中文到英文");
            this.webBrowser1.Navigate("http://translate.google.cn/#");
           
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
           string tranResult = getContent();
           textBox2.ForeColor = Color.Black;
           textBox2.Text = tranResult;
        }
        //过滤相关信息
        private string getContent()
        {
            string value = "";
            HtmlDocument doc = webBrowser1.Document; //获取document对象
            foreach (HtmlElement em in doc.All) //轮循
            {
                string str = em.Id;
                if (str == "result_box")
                {
                    value = em.OuterText;
                }
            }
            return value;
        }
        //互换
        private void GetUrl()
        {
            HtmlElementCollection links = this.webBrowser1.Document.Links;
            foreach (HtmlElement link in links)
            {
                //这里是模糊查找
                if (link.GetAttribute("href").Contains(@""))
                {
                    link.InvokeMember("click"); //激发链接的点击事件
                }
            }
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string text=webBrowser1.Document.Forms["text_form"].Document.GetElementById("old_sl").InnerText;
            if (this.comboBox1.Text.Equals("从英文到中文"))
            {
                this.webBrowser1.Navigate("http://translate.google.cn/#");
            }
            else
            {
                this.GetUrl();
            }
        }