Click here to Skip to main content
Click here to Skip to main content

Opening IE Using C# and Firing Events

By , 4 Nov 2009
 

Introduction

This article shows code to open a website in a new Internet Explorer window and find the controls inside the website and fire the events in that site.

Using the Code

Recently, I came across a requirement for opening a website in Internet Explorer and firing the events in that site (e.g., open GMail and fill the user ID and password and fire the sign-in button event) using C#. It was quite interesting.... The code I used is shown below:

InternetExplorer gmailurl = new InternetExplorer();
object mVal = System.Reflection.Missing.Value;
gmailurl.Navigate("http://www.gmail.com", ref mVal, ref mVal, ref mVal, ref mVal);

HTMLDocument myDoc = new HTMLDocumentClass();
System.Threading.Thread.Sleep(500);
myDoc = (HTMLDocument)gmailurl.Document;
HTMLInputElement userID = (HTMLInputElement)myDoc.all.item("username", 0);
userID.value = "youruserid";
HTMLInputElement pwd = (HTMLInputElement)myDoc.all.item("pwd", 0);
pwd.value = "yourpassword";
HTMLInputElement btnsubmit = (HTMLInputElement)myDoc.all.item("signIn", 0);
btnsubmit.click();
gmailurl.Visible = true;

In the above code, the class InternetExplorer is from SHDocVw.dll, which you can download from: http://www.dll-files.com/dllindex/dll-files.shtml?shdocvw.

Another reference I have used is for the HTMLDocument class is MSHTML, which you can get from a COM reference (right click the project in Solution Explorer and click on Add Reference, go to the COM tab, and add Microsoft HTML Object Library).

In the above code:

HTMLInputElement userID = (HTMLInputElement)myDoc.all.item("username", 0);

is used to find the textbox for the username, where the "username" is nothing but the name of the input textbox control which is used in the GMail site. You can find this by going to the View Source of the GMail site; similarly for the password and the sign-in button.

The code which above will open Internet Explorer on the server side and not on the client side, so I went for a client-script which will do the same job as above. Here is the VBScript code I used:

Function getgmail()
    Dim count
    Dim ie
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Navigate "http://www.gmail.com"
    Do While ie.Busy Or (ie.READYSTATE <> 4)
        count = count+1
    Loop
    ie.Visible=True
    ie.document.all.username.value = "youruserID"
    ie.document.all.pwd.value = "yourpassword"
    ie.document.all.signIn.click
END Function

Points of Interest

I have tried the above solution in many ways; I tried to use ProcessStartInfo, IHTMLDocument, and then the HttpWebRequest class, which didn't satisfied my requirements. Another point which I have noted is in some sites, for some controls, there will not be any name (e.g., username, pwd, signIn ...) property, so I had to struggle a little to find controls, and I found that using the unique IDs for each control used in that site helps.

Hope this helps someone...... Happy Coding! :-)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Anoop_K_V
Software Developer (Senior) UST Global
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralThanks a lot : Press enter on the browsermemberKapilWaghe21 Jan '12 - 3:31 
Hi,
 
This is the what for I was playing the Hide-and-Seek game.
 
Thanks Anoop.
 
You can press the enter on a particular control by :
 
userID.focus();
 
SendKeys.SendWait("{ENTER}");
 
Regards,
Kapil
i m kapil waghe hav done my Bachelor's and Master's in computer application n looking 4 job. b4 i would like 2 have some knowledge abt the latest. i m kapil waghe hav done my Bachelor's and Master's in computer application n looking 4 job. b4 i would like 2 have some knowledge abt the latest. i m kapil waghe hav done my Bachelor's and Master's in computer application n looking 4 job. b4 i would like 2 have some knowledge abt the latest.

QuestionConvert to C#memberatulrungta9 Jan '12 - 6:24 
Function getgmail()
    Dim count
    Dim ie
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Navigate "http://www.gmail.com"
    Do While ie.Busy Or (ie.READYSTATE <> 4)
        count = count+1
    Loop
    ie.Visible=True
    ie.document.all.username.value = "youruserID"
    ie.document.all.pwd.value = "yourpassword"
    ie.document.all.signIn.click
END Function
 

Hi Your code seems to be very good and will really solve my problem i think so. But I am a C# developer and facing problem when i reach on following line.
Set ie = CreateObject("InternetExplorer.Application")
Plz Help Me as soon as possible.
GeneralExample Code for OWA 2010 C# Single Sign OnmemberJimShat9 Aug '11 - 11:50 
Anoop_K_V - You Rock! Because of you they're going to let me outside to see daylight. I have been struggling over an Outlook Web Access 2010 Single Sign On c# solution and your code is the best I've found yet. I've modified your gmail solution to support OWA 2010.
Thanks,
Jim
                   AutoResetEvent documentCompleteOW2010;
        private void button1_Click(object sender, EventArgs e)
        {
            InternetExplorer explorer = new InternetExplorer();
            explorer.DocumentComplete += OnIEDocumentCompleteOWA2010; // Setting the documentComplete Event to false            
            documentCompleteOW2010 = new AutoResetEvent(false);
            object mVal = System.Reflection.Missing.Value;
            explorer.Navigate("https://owa.myorg.com/owa/auth/logon.aspx?replaceCurrent=1&url=https%3a%2f%2fowa.myorg.com%2fowa%2f", ref mVal, ref mVal, ref mVal, ref mVal);// Waiting for the document to load completely            
            documentCompleteOW2010.WaitOne();
            HTMLDocument doc = (HTMLDocument)explorer.Document; 
            HTMLInputElement userID = (HTMLInputElement)doc.all.item("username", 0);
            userID.value = "MyActiveDirectoryLogin";
            HTMLInputElement pwd = (HTMLInputElement)doc.all.item("password", 0);
            pwd.value = "MyActiveDirectoryLoginPassword";
            HTMLInputElement btnsubmit = null;//= (HTMLInputElement)doc.all.item("Signin", 0);
            var tags= doc.getElementsByTagName("input");
            foreach (var VARIABLE in tags)
            {
                var u = (HTMLInputElement)VARIABLE;
                if(u.type=="submit")
                {
                    btnsubmit = u;
                }
            }
            btnsubmit.click();
            explorer.Visible = true;
        }
 
        private void OnIEDocumentCompleteOWA2010(object pDisp, ref object URL)
        {
          
            documentCompleteOW2010.Set();
        }

GeneralMy vote of 2membergg679 Nov '09 - 2:11 
Just an overfly on the subject
Generalcan't executememberMember 66880694 Nov '09 - 19:39 
I'm using VS 2008 SP1
 
I've used a win form and click on button to dislay IE
 
but this error occured:
 
Error HRESULT E_FAIL has been returned from a call to a COM component.
 
(i've referenced and using two dlls: MSHTML and SHDocVw)
 
Let met solution for this problem...
GeneralRe: can't executememberAnoop_K_V4 Nov '09 - 20:16 
Hi
please go through these links;
 
http://forums.asp.net/t/1198955.aspx
or
http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2008/05/01/error-hresult-e-fail-has-been-returned-from-a-call-to-a-com-component.aspx
 
if you are doing it in win forms you can even make use of WebBrowser control
 
http://www.codeproject.com/KB/cs/webbrowser.aspx
GeneralRe: can't executemembersmesser5 Nov '09 - 3:40 
The names he uses for username and password aren't correct. View the source of the google login page to see the correct names.
 
I don't recall off the top of my head as I tried this at home and I am now at work.
 
But I believe for me passwd instead of pwd worked I can't remember on the other input.
 
Some exception handling would be in order. The error is because it can't find a control of the given name. Localization??
 
PS: I used it from a winform just fine.
GeneralRe: can't executememberquangnd.edu5 Nov '09 - 15:24 
Exception fired here:
 
myDoc = (HTMLDocument)gmailurl.Document;
 
And error still is: Error HRESULT E_FAIL has been returned from a call to a COM component.
 
To smesser: If you run it with winform success, send me a copy of source code Smile | :)
 
my email: quangnd.edu@hotmail.com
 
Thanks Smile | :)
GeneralRe: can't execute [modified]membersmesser6 Nov '09 - 19:00 
After a closer look and a little more testing mine doesn't work either unless
I put a breakpoint on the following line:
 
myDoc = (HTMLDocument)gmailurl.Document;
 
Then if I stay in the debugger for several seconds then continue it works fine.
I have tried sleeping for up to 5 seconds without pausing in the debugger and
it still doesn't work.
 
private void button1_Click(object sender, EventArgs e)
{
    InternetExplorer gmailurl = new InternetExplorer();
    object mVal = System.Reflection.Missing.Value;
    gmailurl.Navigate("http://www.gmail.com", ref mVal, ref mVal, ref mVal, ref mVal);
 
    while(gmailurl.Busy)
    {
       System.Threading.Thread.Sleep(100);
    }
 
    HTMLDocument myDoc = (HTMLDocument)gmailurl.Document;
    HTMLInputElement userID = (HTMLInputElement)myDoc.all.item("Email", 0);
    userID.value = "youruserid";
    HTMLInputElement pwd = (HTMLInputElement)myDoc.all.item("Passwd", 0);
    pwd.value = "yourpassword";
    HTMLInputElement btnsubmit = (HTMLInputElement)myDoc.all.item("signIn", 0);
    btnsubmit.click();
    gmailurl.Visible = true;
}
 
EDIT: I have changed the above code and it should now work
 
Note: Ensure that in your gmail home page if you have stay
logged in checked you log out before you use this code else
you will autologged in and the code will fail. Of course you
can check pwd, userId and btnsubmit for null before using them.
 
modified on Saturday, November 7, 2009 1:43 AM

GeneralRe: can't executemembersmesser7 Nov '09 - 10:03 
A another solution:
 
using System;
using System.Threading;
using System.Windows.Forms;
using mshtml;
using SHDocVw;
 
namespace GmailLogin
{
    public partial class Form1 : Form
    {
        AutoResetEvent documentComplete;
        
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            InternetExplorer explorer = new InternetExplorer();
 
            explorer.DocumentComplete += OnIEDocumentComplete;
 
            // Setting the documentComplete Event to false
            documentComplete = new AutoResetEvent(false);
 
            object mVal = System.Reflection.Missing.Value;
            explorer.Navigate("http://www.gmail.com", ref mVal, ref mVal, ref mVal, ref mVal);
 
            // Waiting for the document to load completely
            documentComplete.WaitOne();
 
            HTMLDocument doc = (HTMLDocument)explorer.Document;
 
            HTMLInputElement userID = (HTMLInputElement)doc.all.item("Email", 0);
            userID.value = "youruserid";
            HTMLInputElement pwd = (HTMLInputElement)doc.all.item("Passwd", 0);
            pwd.value = "yourpassword";
            HTMLInputElement btnsubmit = (HTMLInputElement)doc.all.item("signIn", 0);
            btnsubmit.click();
            explorer.Visible = true;
        }
 
        // Definition of the function that sets the documentComplete event to true
        private void OnIEDocumentComplete(object pDisp, ref object URL)
        {
            documentComplete.Set();
        }
    }
}

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 4 Nov 2009
Article Copyright 2009 by Anoop_K_V
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid