问题
I am a starter with c# programming language. I placed a simple web browser into a window form. I assign a url address to the browser and I want to see if the browser successfully opened the link I provided.
I know that there is a eventhandler called
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
however, after assigning the url for the browser, I want to write something like
if (webBrowser1_DocumentCompleted)
{
//my code here
}
is this possible? I know you can use "WebBrowserReadyState" but I would prefer to try and use Document ready.
回答1:
I'm not sure if this is what you are looking for but this is what I would try:
first create an Event Handler in the Constructor of your form class:
public void Form1()
{
webBrowser1.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(WebDocumentCompleted);
}
After this you need to create a method that will be called when that event is fired:
void WebDocumentcompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//Your code here
}
Hope this helps!
回答2:
Because loading and rendering of the webpage is running asynchronously you have to do you logic (which should run after the document is loaded) in the event method. You can subscribe the event in this way:
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
You have to have a method in your class with this signature in which you can make the coding you want:
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Do something after the document is loaded.
}
回答3:
You can inspect the result from DownloadDataCompletedEventArgs
(e)
class Program
{
static void Main(string[] args)
{
WebClient wb = new WebClient();
wb.DownloadDataAsync("www.hotmail.com");
wb.DownloadDataCompleted += new DownloadDataCompletedEventHandler(wb_DownloadDataCompleted);
}
static void wb_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (e.Cancelled)//cancelled download by someone/may be you
{
//add necessary logic here
}
else if (e.Error)// all exception can be collected here including invalid download uri
{
//add necessary logic here
}
else if (e.UserState)// get user state for asyn
{
//add necessary logic here
}
else
{
//you can assume here that you have result from the download.
}
}
}
来源:https://stackoverflow.com/questions/7901701/documentcompleted