[英]Use webBrowser control in aspx website
I am using the following code to use a webBrowser control in an aspx website as a class- 我正在使用以下代码在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;
}
}
This works fine however I wish to add other methods to the class that use the same WebBrowser
object so adding something like - 效果很好,但是我希望向使用相同
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");
}
However I can't access the WebBrowser
object as it is not global and also if I set it as global aspx does not allow this is this possible? 但是我不能访问
WebBrowser
对象,因为它不是全局对象,而且如果我将其设置为全局aspx,则不允许这样做吗?
You do not need to make it global. 您无需将其设置为全局。 You can define a private instance of WebBrowser in your CustomBrowser class like this:
您可以在CustomBrowser类中定义WebBrowser的私有实例,如下所示:
private WebBrowser _browser;
public CustomBrowser()
{
_browser = new WebBrowser();
}
With this, your new methods can access the same instance of WebBrowser, which is _browser
. 这样,您的新方法就可以访问WebBrowser的相同实例,即
_browser
。 Your CustomBrowser class needs to implement IDisposable
interface because WebBrowser is a disposable object. 您的CustomBrowser类需要实现
IDisposable
接口,因为WebBrowser是可抛弃的对象。 For example: 例如:
public void Dispose()
{
if (_browser != null)
{
_browser.Stop();
if (!_browser.IsDisposed)
{
_browser.Dispose();
}
}
}
Reference for implementing IDisposable 实现IDisposable的参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.