user3341951 user3341951 - 13 days ago 4
C# Question

Logging to webpage using WebBrowserControl, but login form is separate

I was able to get this to work before, in a much bigger application, but I did something that broke it :(. This is stripped code to make it simpler. For some reason the "email" field is being clicked on, but no data from the first form is being entered into the field. Is this because it is trying to enter data into the field before anything is typed into it? I would eventually like to be able to log into a page after clicking the login button from a previous form.

Form1 (login form):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string username;
public string password;
public bool isLoggedIn = false;

public void btnLogin_Click(object sender, EventArgs e)
{
Form2 formBrowser = new Form2();
username = textBox1.Text;
password = textBox2.Text;
formBrowser.Show();
isLoggedIn = true;
}


}
}


Form2 (main webbrowser form):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
bool is_sec_page = false;
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
Form1 form1 = new Form1();
if (!is_sec_page && form1.isLoggedIn == true)
{
Form1 formLogin = new Form1();
HtmlElement ele = webBrowser1.Document.GetElementById("email");
ele.InnerText = formLogin.username;
}
is_sec_page = true;
}
}
}

Answer

Because isLoggedIn an instance member initialized with false as default value, if you created a new instance of Form1 and accessing the value of Form1.isLoggedIn will give you the default value. What you can do here is Make that variable as static then you can access it without using instance.

So the declaration of isLoggedIn in Form1 will be like this:

  public static bool isLoggedIn = false;

And you can access them from Form2 like this Form1.isLoggedIn, Similar in the case of other variables as well. Which means the declaration session will be like this:

public static string username;
public static string password;
public static bool isLoggedIn = false; 

And the _DocumentCompleted will be like this:

void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    if (!is_sec_page && Form1.isLoggedIn)
    {           
        HtmlElement ele = webBrowser1.Document.GetElementById("email");
        if(ele != null)            
           ele.InnerText = Form1.username;
    }
    is_sec_page = true;
}