在按钮单击窗体中打开一个网页

时间:2011-09-14 10:31:42

标签: c# .net winforms buttonclick

当我点击表单中的按钮(winform)时,我想显示一个网页(谷歌)....

我已尝试过以下代码,但它对我不起作用.....

   public partial class Form1 : Form {
    bool mHooked;
    public Form1() {
        InitializeComponent();
        webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
        webBrowser1.Navigate("http://www.google.com");
    }

    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
        if (mHooked) return;
        // Get the form
        HtmlDocument doc = webBrowser1.Document;
        HtmlElement form = doc.Forms["f"];
        // Get the "I'm feeling lucky" button
        HtmlElement lucky = form.All["btnI"];
        lucky.Click += lucky_Click;
        mHooked = true;
    }
    void lucky_Click(object sender, EventArgs e) {
        this.Close();
    }
}

我正在使用c#

进行winforms应用程序

任何人都可以帮忙......

非常感谢提前......

3 个答案:

答案 0 :(得分:4)

首先在表单中添加一个按钮,然后在Click事件处理程序中执行此操作

private void button1_Click(object sender, EventArgs e)
{           
   //remove this from the constructor else it will be loaded along with the form
    webBrowser1.Navigate("http://www.google.com");
}

答案 1 :(得分:4)

public partial class Form1 : Form

{

    bool mHooked;

    public Form1()

    {
        InitializeComponent();
        webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
        //webBrowser1.Navigate("http://www.google.com"); 
    }

    private void button1_Click(object sender, EventArgs e)
    {
        webBrowser1.Navigate("http://www.google.com"); 
    }
    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
    {
        if (mHooked) return;   
        // Get the form 
        HtmlDocument doc = webBrowser1.Document; 
        HtmlElement form = doc.Forms["f"];    
        // Get the "I'm feeling lucky" button 
        HtmlElement lucky = form.All["btnI"];
        lucky.Click += button1_Click;   
        mHooked = true;   
    } 
}

答案 2 :(得分:0)

点击按钮添加:

ProcessStartInfo sInfo = new ProcessStartInfo("http://mysite.com/");  
Process.Start(sInfo);

(或)

System.Diagnostics.Process.StartProcessStartInfo sInfo = new ProcessStartInfo("http://mysite.com/");
Process.Start(sInfo);

如果您想使用网页抓取技术从特定网站提取数据或在您的winform中打开网站,请使用网络浏览器控制并尝试ShaliniPavan或V4Vendetta提供的任何答案。