1

我想在网络浏览器中选中复选框时引发一个事件。这是我想出的:

   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);
    }

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

4

1 回答 1

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;
    }
}
于 2013-05-08T16:23:46.300 回答