This blog is moved to
http://amalhashim.wordpress.com

Friday, September 24, 2010

C# | Automating Facebook Login using WebBrowser Control

Create a new windows forms application project.

Add two button and place the web browser control as shown below. Rename the button as “btnShowPage” and “btnLogin”.

image

On form load event use the following code

private void Form1_Load(object sender, EventArgs e)
{
btnLogin.Enabled = false;
}



Now on button btnShowPage use the following code



private void btnShowPage_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("https://login.facebook.com/login.php?login_attempt=1");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}


void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string s = webBrowser1.DocumentText;
btnLogin.Enabled = true;
}



On btnLogin click event use the following code



private void btnLogin_Click(object sender, EventArgs e)
{
HtmlElement ele = webBrowser1.Document.GetElementById("email");
if (ele != null)
ele.InnerText = "amalhashim@gmail.com";

ele = webBrowser1.Document.GetElementById("pass");
if (ele != null)
ele.InnerText = "password";

ele = webBrowser1.Document.GetElementById("Login");
if (ele != null)
ele.InvokeMember("click");
}



That’s it :-)