gpt4 book ai didi

c# - WebBrowser 导航功能不起作用,并且未调用处理程序

转载 作者:行者123 更新时间:2023-11-30 13:58:05 25 4
gpt4 key购买 nike

下面的代码。

我正在尝试导航到一个网站并阅读信息,问题是 Navigate 不起作用,唯一被调用的事件是 Navigating 并且打印的 Url 为空,其他事件从未被调用。我错过了什么?我必须使用 Form 类才能导航吗?我不能从控制台应用程序以编程方式使用它吗?

请帮忙。

class WebNavigator
{
private readonly WebBrowser webBrowser;

public WebNavigator()
{
webBrowser = new WebBrowser
{
AllowNavigation = true
};

webBrowser.Navigated += webBrowser_Navigated;
webBrowser.Navigating += webBrowser_Navigating;
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
}

// Navigates to the given URL if it is valid.
public void Navigate(string address)
{
if (String.IsNullOrEmpty(address)) return;
if (address.Equals("about:blank")) return;
if (!address.StartsWith("http://") &&
!address.StartsWith("https://"))
{
address = "http://" + address;
}
try
{
Trace.TraceInformation("Navigate to {0}", address);
webBrowser.Navigate(new Uri(address));
}
catch (System.UriFormatException)
{
Trace.TraceError("Error");
return;
}
}

// Occurs when the WebBrowser control has navigated to a new document and has begun loading it.
private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
Trace.TraceInformation("Navigated to {0}", webBrowser.Url);
}

// Occurs before the WebBrowser control navigates to a new document.
private void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
Trace.TraceInformation("Navigating to {0}", webBrowser.Url);
}

private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var wb = sender as WebBrowser;
Trace.TraceInformation("DocumentCompleted {0}", wb.Url);
}
}

最佳答案

我会使用 await/async .

用法:

static async void  DoWork()
{
var html = await GetHtmlAsync("http://www.google.com/");
}

实用方法

static Task<string> GetHtmlAsync(string url)
{
var tcs = new TaskCompletionSource<string>();

var thread = new Thread(() =>
{
WebBrowser wb = new WebBrowser();

WebBrowserDocumentCompletedEventHandler documentCompleted = null;
documentCompleted = async (o, s) =>
{
wb.DocumentCompleted -= documentCompleted;
await Task.Delay(2000); //Run JS a few seconds more

tcs.TrySetResult(wb.DocumentText);
wb.Dispose();
Application.ExitThread();
};

wb.ScriptErrorsSuppressed = true;
wb.DocumentCompleted += documentCompleted;
wb.Navigate(url);
Application.Run();
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

return tcs.Task;
}

关于c# - WebBrowser 导航功能不起作用,并且未调用处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18428616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com