Reputation: 1317
I'm having difficulties trying to programmitcally determine the width and height of a webbrowser based on the contents of a fully loaded page. I need this information to capture a screenshot of the webpage.
This occures within a button click event
wbNY.Navigate(new Uri("http://www.website.com"), "_self");
wbNY.DocumentCompleted += wbNY_DocumentCompleted;
This is my document completed code
private void wbNY_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url == wbNY.Url)
{
if (wbNY.ReadyState == WebBrowserReadyState.Complete)
{
DoPageChecks();
}
}
}
Within DoPageChecks I call this method
TakeScreenshot(wbNY);
This is my TakeScreenshot method
protected void TakeScreenshot(WebBrowser wb)
{
Size pageSize = new Size(wb.Document.Window.Size.Width,wb.Document.Window.Size.Height)
}
My screenshot code works fine, so I'm just showing everything up to the point where I'm trying to get the height and width of the webbrowser contents, so that I can take a screenshot with the correct dimensions.
I've also tried
Size pageSize = new Size(wb.Document.Body.ScrollRectangle.Width,wb.Document.Body.ScrollRectangle.Height)
But this also isn't giving the correct values.
More specifically, height is coming over as 0, or a sometimes ~20px, when the real result should be closer to 800px+
Upvotes: 2
Views: 12278
Reputation: 1317
Ultimately I went ahead and found mshtml had the tools to obtain the width/height.
The final screenshot method:
protected void TakeScreenshot(WebBrowser wb)
{
mshtml.IHTMLDocument2 docs2 = (mshtml.IHTMLDocument2)wbNY.Document.DomDocument;
mshtml.IHTMLDocument3 docs3 = (mshtml.IHTMLDocument3)wbNY.Document.DomDocument;
mshtml.IHTMLElement2 body2 = (mshtml.IHTMLElement2)docs2.body;
mshtml.IHTMLElement2 root2 = (mshtml.IHTMLElement2)docs3.documentElement;
int width = Math.Max(body2.scrollWidth, root2.scrollWidth);
int height = Math.Max(root2.scrollHeight, body2.scrollHeight);
// Resize the control to the exact size to display the page. Also, make sure scroll bars are disabled
wb.Width = width;
wb.Height = height;
Bitmap bitmap = new Bitmap(width, height);
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, width, height));
bitmap.Save(SaveImgDirectory + filename);
}
Upvotes: 4
Reputation: 398
You want to get ActualHeight and ActualWidth, they return the rendered height and width of the Window, which is what you want if you are taking a screenshot.
Upvotes: 0