我已经编写了一些代码来向网站发布消息。它工作正常(对于第一个实例),问题是它一直在webBrowser1_DocumentCompleted方法中循环(一遍又一遍地运行SendData方法)。所以我一定不能正确处理这个事件。在运行SendData调用一次后,我希望它返回到最初启动的button1_Start_Click事件。
private void button1_Start_Click(object sender, EventArgs e)
{
GetData();
}
private void GetData()
{
webBrowser1.Navigate(inputURLID);
}
private void SendData()
{
webBrowser1.Document.GetElementById("subject").SetAttribute("value", textBox2_Subject.Text);//To (username)
webBrowser1.Document.GetElementById("message").SetAttribute("value", richTextBox1.Text);//Subject
webBrowser1.Document.GetElementById("Submit").InvokeMember("click");//Message
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
SendData();
}
答案 0 :(得分:0)
问题在于,当您单击“提交”时,将加载新页面并再次为此新页面调用DocumentCompleted。
您可以尝试这样的事情:
bool documentCompleted = false;
private void button1_Start_Click(object sender, EventArgs e)
{
webBrowser1.Navigate(inputURLID);
WaitForDocumentCompleted();
SendData();
WaitForDocumentCompleted();
}
private void WaitForDocumentCompleted()
{
while (!documentCompleted)
{
Thread.Sleep(100);
Application.DoEvents();
}
documentCompleted = false;
}
private void SendData()
{
webBrowser1.Document.GetElementById("subject").SetAttribute("value", textBox2_Subject.Text);//To (username)
webBrowser1.Document.GetElementById("message").SetAttribute("value", richTextBox1.Text);//Subject
webBrowser1.Document.GetElementById("Submit").InvokeMember("click");//Message
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
documentCompleted = true;
}
答案 1 :(得分:0)
我必须发帖,你选择的答案会让你陷入困境。解决方法很简单,您只需要一个变量来告诉您下一个DocumentCompleted事件就是您感兴趣的事件。就像这样:
private bool WaitingForData;
private void GetData()
{
webBrowser1.Navigate(inputURLID);
WaitingForData = true;
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (WaitingForData) SendData();
WaitingForData = false;
}