Thursday, 26 June 2014

Catch HTML Page Events in Web Browser Control

Hello,Here is simple example to catch HTML document's control's events in Web browser control in winform.

1. Add browser control in your form. and register its CodumentCompleted  Event in constructor of form.2. Add Html document url in browser control.3. Find HTML control in Webbrowser control's event and register HTMl control's event.4.  Now you can catch HTML control's Event in your winform


// Initialize control and its event
public Form1()
        {
            InitializeComponent();
            brwWebBrowser.DocumentCompleted += WebBrowser1_DocumentCompleted;    
        }

private void WebBrowser1_DocumentCompleted(System.Object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
               // Get HTML Element from HTML document
                HtmlElement Elem_btn = brwWebBrowser.Document.GetElementById("btnSave");
                if (Elem_btn != null)
                {
                    Elem_btn.Click += Elem_btn_Click;
                }

            }
            catch (Exception ex)
            {
               
            }
        }

 void Elem_btn_Click(object sender, HtmlElementEventArgs e)
        {
            HtmlElement Elem = brwWebBrowser.Document.GetElementById("txt");

            if ((Elem != null))
            {
                // Get Value from control's attribute
                string Temp_Val = Elem.GetAttribute("value");
                string strVal = Elem.GetAttribute("value");
            }
        }



HTML Page

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>  
</head>
<body>

    <input type="text" id="txt" />
    <input type="button" id="btnSave" value="Save" />

</body>

</html>

No comments:

Post a comment