在C#中选中Web浏览器的复选框时引发事件

时间:2013-05-04 11:44:25

标签: c# events browser

我想在网络浏览器中选中复选框时引发事件。 以下是我的想法:

   public class HTMLCheckBoxArgs : EventArgs
   {
      public Guid ElementGuid;
   }
    public delegate void CheckBoxChangeEventHandler(object sender, HTMLCheckBoxArgs e);
    public event CheckBoxChangeEventHandler CheckPressed;

    void OnCheckPressed(HTMLCheckBoxArgs args)
    {
        if (CheckPressed != null)
            CheckPressed(this, args);
    }

    protected void CheckBoxEvents() 
    {
        HtmlElementCollection elements = webBrowser1.Document.GetElementsByTagName("input");
        foreach (HtmlElement el in elements)
        {
            HTMLCheckBoxArgs checkbargs = new HTMLCheckBoxArgs();
            if (el.GetAttribute("type") == "checkbox")
            {
                    checkbargs.ElementGuid = Guid.Parse(el.Id);
                    el.AttachEventHandler("onclick", (sender, args) => OnCheckBoxClicked(el, checkbargs));

            }
        }
    }

    public void OnCheckBoxClicked(object sender, EventArgs args)
    {
        OnCheckPressed((HTMLCheckBoxArgs)args);
    }

我遇到的问题是,这样我点击复选框时会引发事件。 我希望在选中复选框时引发事件。

1 个答案:

答案 0 :(得分:2)

试试这个:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.DocumentText = "<html><body><input type=\"checkbox\" id=\"chk\" value=\"some\">some thing</body></html>";
    }

    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        foreach (HtmlElement el in webBrowser1.Document.All)
        {
            if (el.GetAttribute("type") == "checkbox")
            {
                el.AttachEventHandler("onclick", (send, args) => OnElementClicked(el, EventArgs.Empty));
            }

        }

    }

    private object OnElementClicked(HtmlElement el, EventArgs eventArgs)
    {
        if (el.GetAttribute("checked") == "True")
        {
            MessageBox.Show("checked");
        }
        return false;
    }
}