所以我有这个应用程序,它将帮助我为我的一些客户发送电子邮件,并且一切正常,直到它到达最后一次调用。它按下按钮并让我登录,但随后它继续运行代码并再次循环回到按钮单击,这给我一个错误,因为按钮不再存在,因为我们已经登录所以 HtmlDocument 不再相同了. 我试图退货;最后,但这并没有阻止我的代码运行,我在这一点上相当迷失。我试过用断点调试它,它似乎是,正如我提到的再次循环代码。
异常消息:System.NullReferenceException:“对象引用未设置为对象的实例。”
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 NoTheme
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.Navigate("https://accounts.google.com/ServiceLogin#identifier");
}
private void button1_Click(object sender, EventArgs e)
{
HtmlDocument startDoc = webBrowser1.Document;
HtmlElement usernameElement = startDoc.GetElementById("Email");
HtmlElement loginBtnElement = startDoc.GetElementById("signIn");
usernameElement.SetAttribute("value", "theGmail@gmail.com");
loginBtnElement.InvokeMember("click");
webBrowser1.DocumentCompleted += WebBrowser1_DocumentCompleted;
}
private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlDocument startDoc = webBrowser1.Document;
HtmlElement usernameElement = startDoc.GetElementById("Passwd");
HtmlElement loginBtnElement = startDoc.GetElementById("signIn");
usernameElement.SetAttribute("value", "thePassword"); //this is where it throws the error
loginBtnElement.InvokeMember("click");
}
}
}