How to print full content of win form c# [duplicate] - c#

I have a windows forms project written in C#. The main form has a TabControl on it and there is a requirement for one of the users to be able to print one of the TabPages. The form is very long and I use a vertical scroll bar. The whole of the form needs to be able to be printed.
I have tried using the DrawToBitmap method to convert to a bitmap first, but this will only include the portion of the form that the user can see. Some other solutions I have tried involve screen capturing, which has the same issue.
How can I print out, or get an image, of the whole of the tab page, including the parts the user only sees when they scroll down?

This is rather simple for any control including TabControls and TabPages but not Forms.
All you need to do is enlarge the relevant controls enough to show all their content. (They don't have to be actually visible on screen.)
Here is an example:
tabControl1.Height = 10080;
tabPage2.Height = 10050;
dataGridView1.Height = 10000;
dataGridView1.Rows.Add(3000);
for (int i = 0; i < dataGridView1.Rows.Count; i++) dataGridView1[0, i].Value = i;
using (Bitmap bmp = new Bitmap(tabControl1.Width , tabControl1.Height ))
{
tabControl1.DrawToBitmap(bmp, tabControl1.ClientRectangle);
bmp.Save("D:\\xxxx.png", ImageFormat.Png);
}
This saves the full content of the DataGridView, the TabPage and the TabControl..
Note: that this will not work with forms, which can't much exceed the screen dimensions..
Update: Here is code that saves a form with vertical scrolling by patching several bitmaps together. It can, of course be expanded to include horizontal scrolling as well. I have coded a similar solution for larger Panels here.
static void saveLargeForm(Form form, string fileName)
{
// yes it may take a while
form.Cursor = Cursors.WaitCursor;
// allocate target bitmap and a buffer bitmap
Bitmap target = new Bitmap(form.DisplayRectangle.Width, form.DisplayRectangle.Height);
Bitmap buffer = new Bitmap(form.Width, form.Height);
// the vertical pointer
int y = 0;
var vsc = form.VerticalScroll;
vsc.Value = 0;
form.AutoScrollPosition = new Point(0, 0);
// the scroll amount
int l = vsc.LargeChange;
Rectangle srcRect = ClientBounds(form);
Rectangle destRect = Rectangle.Empty;
bool done = false;
// we'll draw onto the large bitmap with G
using (Graphics G = Graphics.FromImage(target))
{
while (!done)
{
destRect = new Rectangle(0, y, srcRect.Width, srcRect.Height);
form.DrawToBitmap(buffer, new Rectangle(0, 0, form.Width, form.Height));
G.DrawImage(buffer, destRect, srcRect, GraphicsUnit.Pixel);
int v = vsc.Value;
vsc.Value = vsc.Value + l;
form.AutoScrollPosition = new Point(form.AutoScrollPosition.X, vsc.Value + l);
int delta = vsc.Value - v;
done = delta < l;
y += delta;
}
destRect = new Rectangle(0, y, srcRect.Width, srcRect.Height);
form.DrawToBitmap(buffer, new Rectangle(0, 0, form.Width, form.Height));
G.DrawImage(buffer, destRect, srcRect, GraphicsUnit.Pixel);
}
// write result to disc and clean up
target.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
target.Dispose();
buffer.Dispose();
GC.Collect(); // not sure why, but it helped
form.Cursor = Cursors.Default;
}
It makes use of a helper function to determine the the net size of the virtual client rectangle, ie excluding borders, title and scrollbar:
static Rectangle ClientBounds(Form f)
{
Rectangle rc = f.ClientRectangle;
Rectangle rb = f.Bounds;
int sw = SystemInformation.VerticalScrollBarWidth;
var vsc = f.VerticalScroll;
int bw = (rb.Width - rc.Width - (vsc.Visible ? sw : 0) ) / 2;
int th = (rb.Height - rc.Height) - bw * 2;
return new Rectangle(bw, th + bw, rc.Width, rc.Height );
}

Related

C# form size does not match

I have a c# form that I setup with
int INTERFACE_right = 20;
int INTERFACE_down = 25;
int INTERFACE_width = 846;
int INTERFACE_height = 60;
this.Left = INTERFACE_right;
this.Top = INTERFACE_down;
this.Size = new Size(INTERFACE_width, INTERFACE_height);
And I copy a part of the screen with (I hide the form before with the opacity) with the exact same parameter. So the form should be exactly on top of the part of the screen I copy:
Bitmap grabOnScreen(){
Rectangle rect = new Rectangle(INTERFACE_right, INTERFACE_down, INTERFACE_width, INTERFACE_height);
Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
//bmp.Save("test.jpg", ImageFormat.Jpeg);
return bmp;
}
As I save the image to test.jpg, I know I grab the good part of the screen with the right dimensions etc.
The form should have the same size, and the same location than where I grab the picture, but in pratice the form is bigger than the picture, but as the good location.
How can I match the form size to the same than the rect where i grab the picture ?

Winforms - how to print the whole of a form, including unseen parts?

I have a windows forms project written in C#. The main form has a TabControl on it and there is a requirement for one of the users to be able to print one of the TabPages. The form is very long and I use a vertical scroll bar. The whole of the form needs to be able to be printed.
I have tried using the DrawToBitmap method to convert to a bitmap first, but this will only include the portion of the form that the user can see. Some other solutions I have tried involve screen capturing, which has the same issue.
How can I print out, or get an image, of the whole of the tab page, including the parts the user only sees when they scroll down?
This is rather simple for any control including TabControls and TabPages but not Forms.
All you need to do is enlarge the relevant controls enough to show all their content. (They don't have to be actually visible on screen.)
Here is an example:
tabControl1.Height = 10080;
tabPage2.Height = 10050;
dataGridView1.Height = 10000;
dataGridView1.Rows.Add(3000);
for (int i = 0; i < dataGridView1.Rows.Count; i++) dataGridView1[0, i].Value = i;
using (Bitmap bmp = new Bitmap(tabControl1.Width , tabControl1.Height ))
{
tabControl1.DrawToBitmap(bmp, tabControl1.ClientRectangle);
bmp.Save("D:\\xxxx.png", ImageFormat.Png);
}
This saves the full content of the DataGridView, the TabPage and the TabControl..
Note: that this will not work with forms, which can't much exceed the screen dimensions..
Update: Here is code that saves a form with vertical scrolling by patching several bitmaps together. It can, of course be expanded to include horizontal scrolling as well. I have coded a similar solution for larger Panels here.
static void saveLargeForm(Form form, string fileName)
{
// yes it may take a while
form.Cursor = Cursors.WaitCursor;
// allocate target bitmap and a buffer bitmap
Bitmap target = new Bitmap(form.DisplayRectangle.Width, form.DisplayRectangle.Height);
Bitmap buffer = new Bitmap(form.Width, form.Height);
// the vertical pointer
int y = 0;
var vsc = form.VerticalScroll;
vsc.Value = 0;
form.AutoScrollPosition = new Point(0, 0);
// the scroll amount
int l = vsc.LargeChange;
Rectangle srcRect = ClientBounds(form);
Rectangle destRect = Rectangle.Empty;
bool done = false;
// we'll draw onto the large bitmap with G
using (Graphics G = Graphics.FromImage(target))
{
while (!done)
{
destRect = new Rectangle(0, y, srcRect.Width, srcRect.Height);
form.DrawToBitmap(buffer, new Rectangle(0, 0, form.Width, form.Height));
G.DrawImage(buffer, destRect, srcRect, GraphicsUnit.Pixel);
int v = vsc.Value;
vsc.Value = vsc.Value + l;
form.AutoScrollPosition = new Point(form.AutoScrollPosition.X, vsc.Value + l);
int delta = vsc.Value - v;
done = delta < l;
y += delta;
}
destRect = new Rectangle(0, y, srcRect.Width, srcRect.Height);
form.DrawToBitmap(buffer, new Rectangle(0, 0, form.Width, form.Height));
G.DrawImage(buffer, destRect, srcRect, GraphicsUnit.Pixel);
}
// write result to disc and clean up
target.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
target.Dispose();
buffer.Dispose();
GC.Collect(); // not sure why, but it helped
form.Cursor = Cursors.Default;
}
It makes use of a helper function to determine the the net size of the virtual client rectangle, ie excluding borders, title and scrollbar:
static Rectangle ClientBounds(Form f)
{
Rectangle rc = f.ClientRectangle;
Rectangle rb = f.Bounds;
int sw = SystemInformation.VerticalScrollBarWidth;
var vsc = f.VerticalScroll;
int bw = (rb.Width - rc.Width - (vsc.Visible ? sw : 0) ) / 2;
int th = (rb.Height - rc.Height) - bw * 2;
return new Rectangle(bw, th + bw, rc.Width, rc.Height );
}

Selenium WebDriver C# Full Website Screenshots With ChromeDriver and FirefoxDriver

When I take screenshots with ChromeDriver I get screens with the size of my viewport.
When I take screenshots with FirefoxDriver I get what I want, which is a full screen print of a website.
ChromeDriver is declared like this:
IWebDriver driver = new ChromeDriver();
FirefoxDriver is declared like this:
IWebDriver driver = new FirefoxDriver();
Both drivers execute identical code:
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl(url);//url is a string variable
ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
Screenshot screenshot = screenshotDriver.GetScreenshot();
screenshot.SaveAsFile("c:/test.png", ImageFormat.Png);
ChromeDriver's test.png is of 1920x1099 resolution and contains only the browser viewport.
FirefoxDriver's test.png is of 1903x16559 resolution and contains the whole page.
I know that GetScreenshot() method doesn't return identical resolution sizes because it has slightly different implementations in IEDriver, FirefoxDriver, OperaDriver, ChromeDriver.
My questions are:
Why is there such difference between ChromeDriver's and FirefoxDriver's .GetScreenshot() method, even tho they use an identical interface (ITakesScreenshot)?
Is there a way to make ChromeDriver's GetScreenshot() method return the whole webpage screen instead of just the viewport?
we can't get the entire page screenshot with ChromeDriver2, we need to go for manual implementation.I have modified a method with is available in a blog which works fine with ChromeDriver.
use this method as following :
private IWebDriver _driver = new ChromeDriver(CHROME_DRIVER_PATH);
screenshot.SaveAsFile(saveFileName, ImageFormat.Jpeg);
public Bitmap GetEntereScreenshot()
{
Bitmap stitchedImage = null;
try
{
long totalwidth1 = (long)((IJavaScriptExecutor)_driver).ExecuteScript("return document.body.offsetWidth");//documentElement.scrollWidth");
long totalHeight1 = (long)((IJavaScriptExecutor)_driver).ExecuteScript("return document.body.parentNode.scrollHeight");
int totalWidth = (int)totalwidth1;
int totalHeight = (int)totalHeight1;
// Get the Size of the Viewport
long viewportWidth1 = (long)((IJavaScriptExecutor)_driver).ExecuteScript("return document.body.clientWidth");//documentElement.scrollWidth");
long viewportHeight1 = (long)((IJavaScriptExecutor)_driver).ExecuteScript("return window.innerHeight");//documentElement.scrollWidth");
int viewportWidth = (int)viewportWidth1;
int viewportHeight = (int)viewportHeight1;
// Split the Screen in multiple Rectangles
List<Rectangle> rectangles = new List<Rectangle>();
// Loop until the Total Height is reached
for (int i = 0; i < totalHeight; i += viewportHeight)
{
int newHeight = viewportHeight;
// Fix if the Height of the Element is too big
if (i + viewportHeight > totalHeight)
{
newHeight = totalHeight - i;
}
// Loop until the Total Width is reached
for (int ii = 0; ii < totalWidth; ii += viewportWidth)
{
int newWidth = viewportWidth;
// Fix if the Width of the Element is too big
if (ii + viewportWidth > totalWidth)
{
newWidth = totalWidth - ii;
}
// Create and add the Rectangle
Rectangle currRect = new Rectangle(ii, i, newWidth, newHeight);
rectangles.Add(currRect);
}
}
// Build the Image
stitchedImage = new Bitmap(totalWidth, totalHeight);
// Get all Screenshots and stitch them together
Rectangle previous = Rectangle.Empty;
foreach (var rectangle in rectangles)
{
// Calculate the Scrolling (if needed)
if (previous != Rectangle.Empty)
{
int xDiff = rectangle.Right - previous.Right;
int yDiff = rectangle.Bottom - previous.Bottom;
// Scroll
//selenium.RunScript(String.Format("window.scrollBy({0}, {1})", xDiff, yDiff));
((IJavaScriptExecutor)_driver).ExecuteScript(String.Format("window.scrollBy({0}, {1})", xDiff, yDiff));
System.Threading.Thread.Sleep(200);
}
// Take Screenshot
var screenshot = ((ITakesScreenshot)_driver).GetScreenshot();
// Build an Image out of the Screenshot
Image screenshotImage;
using (MemoryStream memStream = new MemoryStream(screenshot.AsByteArray))
{
screenshotImage = Image.FromStream(memStream);
}
// Calculate the Source Rectangle
Rectangle sourceRectangle = new Rectangle(viewportWidth - rectangle.Width, viewportHeight - rectangle.Height, rectangle.Width, rectangle.Height);
// Copy the Image
using (Graphics g = Graphics.FromImage(stitchedImage))
{
g.DrawImage(screenshotImage, rectangle, sourceRectangle, GraphicsUnit.Pixel);
}
// Set the Previous Rectangle
previous = rectangle;
}
}
catch (Exception ex)
{
// handle
}
return stitchedImage;
}
I cleaned up #Selvantharajah Roshanth's answer and added a check so that it won't try to stitch together screenshots that already fit in the viewport.
public Image GetEntireScreenshot()
{
// Get the total size of the page
var totalWidth = (int) (long) ((IJavaScriptExecutor) driver).ExecuteScript("return document.body.offsetWidth"); //documentElement.scrollWidth");
var totalHeight = (int) (long) ((IJavaScriptExecutor) driver).ExecuteScript("return document.body.parentNode.scrollHeight");
// Get the size of the viewport
var viewportWidth = (int) (long) ((IJavaScriptExecutor) driver).ExecuteScript("return document.body.clientWidth"); //documentElement.scrollWidth");
var viewportHeight = (int) (long) ((IJavaScriptExecutor) driver).ExecuteScript("return window.innerHeight"); //documentElement.scrollWidth");
// We only care about taking multiple images together if it doesn't already fit
if (totalWidth <= viewportWidth && totalHeight <= viewportHeight)
{
var screenshot = driver.TakeScreenshot();
return ScreenshotToImage(screenshot);
}
// Split the screen in multiple Rectangles
var rectangles = new List<Rectangle>();
// Loop until the totalHeight is reached
for (var y = 0; y < totalHeight; y += viewportHeight)
{
var newHeight = viewportHeight;
// Fix if the height of the element is too big
if (y + viewportHeight > totalHeight)
{
newHeight = totalHeight - y;
}
// Loop until the totalWidth is reached
for (var x = 0; x < totalWidth; x += viewportWidth)
{
var newWidth = viewportWidth;
// Fix if the Width of the Element is too big
if (x + viewportWidth > totalWidth)
{
newWidth = totalWidth - x;
}
// Create and add the Rectangle
var currRect = new Rectangle(x, y, newWidth, newHeight);
rectangles.Add(currRect);
}
}
// Build the Image
var stitchedImage = new Bitmap(totalWidth, totalHeight);
// Get all Screenshots and stitch them together
var previous = Rectangle.Empty;
foreach (var rectangle in rectangles)
{
// Calculate the scrolling (if needed)
if (previous != Rectangle.Empty)
{
var xDiff = rectangle.Right - previous.Right;
var yDiff = rectangle.Bottom - previous.Bottom;
// Scroll
((IJavaScriptExecutor) driver).ExecuteScript(String.Format("window.scrollBy({0}, {1})", xDiff, yDiff));
}
// Take Screenshot
var screenshot = driver.TakeScreenshot();
// Build an Image out of the Screenshot
var screenshotImage = ScreenshotToImage(screenshot);
// Calculate the source Rectangle
var sourceRectangle = new Rectangle(viewportWidth - rectangle.Width, viewportHeight - rectangle.Height, rectangle.Width, rectangle.Height);
// Copy the Image
using (var graphics = Graphics.FromImage(stitchedImage))
{
graphics.DrawImage(screenshotImage, rectangle, sourceRectangle, GraphicsUnit.Pixel);
}
// Set the Previous Rectangle
previous = rectangle;
}
return stitchedImage;
}
private static Image ScreenshotToImage(Screenshot screenshot)
{
Image screenshotImage;
using (var memStream = new MemoryStream(screenshot.AsByteArray))
{
screenshotImage = Image.FromStream(memStream);
}
return screenshotImage;
}
It appears as though full-screen screenshots are not yet implemented in the ChromeDriver, due to some inaccuracies in its previous implementation.
Source: https://code.google.com/p/chromedriver/issues/detail?id=294
I have recently written a Selenium based application to test an Internet Explorer UI and found that:
Taking screenshots with selenium was not as quick as using .NET, and
Selenium is unable to take screenshots when dialog boxes are present. This was a major drawback, as I needed to identify unexpected dialogs during interaction with the pages.
Investigate using the Graphics.CopyFromScreen method in System.Drawing as an alternative solution until the feature is implemented in Chrome. Once you have tried .the Net approach however, I don't think you will look back =]
I stumbled accross the same problem and ChromeDriver2 just does not support it.
So I created a little script which scrolls thru the page, takes screenshots and stitches everything together.
You can find the script in my blog post here:
http://dev.flauschig.ch/wordpress/?p=341

Draw persistent grid in TabPage (.Net, C#)

I need to display a persistent grid in a TabPage. My problems would be instantly solved if I could draw to the entire non-visible portion of the TabPage and prevent graphics from being erased when scrolling.
The only other solution I can think of is tracking the scroll position in the tab and basing the grid drawn from that.
To get this to draw in the first place, I had to create an EventHandler for TabPage.Paint.
//Code removed
This method draws vertical and horizontal lines to create a grid within the visible tab, but it continues to draw whenever a Paint event occurs (i.e. scrolling), so it creates overlapping lines and aren't aligned to anything but the size of the current visible area of the tab.
Maybe something like this will work for you:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
const int gridSpacing = 20;
const int lineThickness = 1;
Bitmap bmp = new Bitmap(gridSpacing, gridSpacing);
using (System.Drawing.Pen pen = new System.Drawing.Pen(Color.Blue, lineThickness))
{
using (Graphics G = Graphics.FromImage(bmp))
{
G.Clear(this.BackColor);
G.DrawLine(pen, 0, bmp.Height - pen.Width, bmp.Width, bmp.Height - pen.Width); // horizontal
G.DrawLine(pen, bmp.Width - pen.Width, 0, bmp.Width - pen.Width, bmp.Height); // vertical
}
}
foreach (TabPage TP in tabControl1.TabPages)
{
TP.BackgroundImage = bmp;
TP.BackgroundImageLayout = ImageLayout.Tile;
}
}
}
Keep in mind that this solution is just pseudo. You also have to respond to scrolling.
void form_draw()
{
spacingX = offsetX % scale * -1;
spacingY = offsetY % scale * -1;
if (form.HorizontalPosition != lastXPosition && form.VerticalPosition == lastYPosition)
lastStartX += spacingX;
else if (tab.HorizontalScroll.Value == lastXPosition && form.VerticalPosition != lastYPosition)
lastStartY += spacingY;
lastYPosition = form.VerticalPosition;
lastXPosition = form.HorizontalPosition;
for (int i = lastStartY; i < formHeight; i += scale)
form.draw(0, i, formWidth, i);
for (int i = lastStartX; i < formWidth; i += scale)
form.draw(i, 0, i, formWidth);
}

C# images cropping,splitting,saving

as stated in subject, i have an image:
private Image testing;
testing = new Bitmap(#"sampleimg.jpg");
I would like to split it into 3 x 3 matrix meaning 9 images in total and save it.Any tips or tricks to do this simple? I'm using visual studios 2008 and working on smart devices. Tried some ways but i can't get it. This is what i tried:
int x = 0;
int y = 0;
int width = 3;
int height = 3;
int count = testing.Width / width;
Bitmap bmp = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bmp);
for (int i = 0; i < count; i++)
{
g.Clear(Color.Transparent);
g.DrawImage(testing, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
bmp.Save(Path.ChangeExtension(#"C\AndrewPictures\", String.Format(".{0}.bmp",i)));
x += width;
}
Depending on the .NET version, you could do one of the following to crop:
.NET 2.0
private static Image cropImage(Image img, Rectangle cropArea)
{
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea,
bmpImage.PixelFormat);
return (Image)(bmpCrop);
}
Or .NET 3.5+
// Create an Image element.
Image croppedImage = new Image();
croppedImage.Width = 200;
croppedImage.Margin = new Thickness(5);
// Create a CroppedBitmap based off of a xaml defined resource.
CroppedBitmap cb = new CroppedBitmap(
(BitmapSource)this.Resources["masterImage"],
new Int32Rect(30, 20, 105, 50)); //select region rect
croppedImage.Source = cb; //set image source to cropped
As you can see, it's a bit more simple than what you're doing. The first example clones the current image and takes a subset of it; the second example uses CroppedBitmap, which supports taking a section of the image right from the constructor.
The splitting part is simple maths, just splitting the image into 9 sets of coordinates and passing them into the constructor.

Categories