To print images in windows forms Graphics class and its various methods are used. Graphics class provides methods for sending objects to a device such as printer. Add a printDocument, printDialog and a button to the windows form application.
In the code behind file create an object of Bitmap class which will be used to create an image. Write a function to capture the screen to be printed just like written in the below code:
In the click event of code write the following code:
Print page event of print document should be look like:
Run the project and click on print button. On the print Dialog box click on ok with selected printer and it will print whatever is on your screen at the given points. When I print this then it had printed as the following image:
See also: Printing Text
In the code behind file create an object of Bitmap class which will be used to create an image. Write a function to capture the screen to be printed just like written in the below code:
private void CaptureScreen()
{
Graphics graphics = this.CreateGraphics();
graphics.DrawRectangle(Pens.Black, 50, 50, 300, 100);
image = new Bitmap(300, 300, graphics);
Graphics g = Graphics.FromImage(image);
g.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, this.Size);
}
In the above code a rectangle will be drawn at the given location. CopyFromScreen() function used to performs a bit-block transfer of the color data, corresponding to a rectangle of pixels, from the screen to the drawing surface.{
Graphics graphics = this.CreateGraphics();
graphics.DrawRectangle(Pens.Black, 50, 50, 300, 100);
image = new Bitmap(300, 300, graphics);
Graphics g = Graphics.FromImage(image);
g.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, this.Size);
}
In the click event of code write the following code:
CaptureScreen();
printDocument1.PrintPage += printDocument_PrintPage;
printDialog1.Document = printDocument1;
DialogResult res = printDialog1.ShowDialog();
if (res == DialogResult.OK)
printDocument1.Print();
The above code is somewhat same to the code used in printing text except the calling of CaptureScreen() method.printDocument1.PrintPage += printDocument_PrintPage;
printDialog1.Document = printDocument1;
DialogResult res = printDialog1.ShowDialog();
if (res == DialogResult.OK)
printDocument1.Print();
Print page event of print document should be look like:
void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawImage(image, 50, 100);
}
{
e.Graphics.DrawImage(image, 50, 100);
}
Run the project and click on print button. On the print Dialog box click on ok with selected printer and it will print whatever is on your screen at the given points. When I print this then it had printed as the following image:
See also: Printing Text