我使用以下代码在aspx网站中将webBrowser控件用作类 -
public CustomBrowser()
{
//
// TODO: Add constructor logic here
//
}
protected string _url;
string html = "";
public string GetWebpage(string url)
{
_url = url;
// WebBrowser is an ActiveX control that must be run in a
// single-threaded apartment so create a thread to create the
// control and generate the thumbnail
Thread thread = new Thread(new ThreadStart(GetWebPageWorker));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
string s = html;
return s;
}
protected void GetWebPageWorker()
{
using (WebBrowser browser = new WebBrowser())
{
// browser.ClientSize = new Size(_width, _height);
browser.ScrollBarsEnabled = false;
browser.ScriptErrorsSuppressed = true;
browser.Navigate(_url);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
// Wait for control to load page
while (browser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
html = browser.DocumentText;
}
}
这很好但是我希望在使用相同WebBrowser
对象的类中添加其他方法,所以添加类似的东西 -
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (browser.Document.Body.InnerHtml != null)
{
browse();
}
}
private void browse(object sender, EventArgs e)
{
browser.Navigate("url");
}
但是我无法访问WebBrowser
对象,因为它不是全局的,如果我将其设置为全局aspx不允许这可能吗?
答案 0 :(得分:1)
您无需将其设为全局。您可以在CustomBrowser类中定义WebBrowser的私有实例,如下所示:
private WebBrowser _browser;
public CustomBrowser()
{
_browser = new WebBrowser();
}
通过这种方式,您的新方法可以访问同一个WebBrowser实例,即_browser
。您的CustomBrowser类需要实现IDisposable
接口,因为WebBrowser是一次性对象。例如:
public void Dispose()
{
if (_browser != null)
{
_browser.Stop();
if (!_browser.IsDisposed)
{
_browser.Dispose();
}
}
}
的参考