Tuesday, February 23, 2010

Print a Text File in C#

In this article, you will learn how to print a text file in C#.

Step 1.
Create a Windows Forms application using Visual Studio and add two Button and one TextBox controls to the Form. Change names for the Buttons to Browse and Print respectively.

Step 2.
Write the following code on the Browse button click event handler.
     OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog";
fdlg.InitialDirectory = @"C:\ ";
fdlg.Filter = "Text files (*.txt | .txt | All files (*.*) | *.*";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName;
}
Step 3.
Before we write code on the Print button click event handler, define two private variables on class level.
private Font verdana10Font;
private StreamReader reader;
Now import these two namespace.
using System.IO;
using System.Drawing.Printing;
Write the following code on Print button click event handler.
string filename=textBox1.Text.ToString();
//Create a StreamReader object
reader = new StreamReader (filename);
//Create a Verdana font with size 10
verdana10Font = new Font ("Verdana", 10);
//Create a PrintDocument object
PrintDocument pd = new PrintDocument();
//Add PrintPage event handler
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
//Call Print Method
pd.Print();
//Close the reader
if (reader != null)
reader.Close();
And add the following method to the class.
private void PrintTextFileHandler (object sender, PrintPageEventArgs ppeArgs)
{
//Get the Graphics object
Graphics g = ppeArgs.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
//Read margins from PrintPageEventArgs
float leftMargin = ppeArgs.MarginBounds.Left;
float topMargin = ppeArgs.MarginBounds.Top;
string line = null;
//Calculate the lines per page on the basis of the height of the page and the height of the font
linesPerPage = ppeArgs.MarginBounds.Height/verdana10Font.GetHeight(g);
//Now read lines one by one, using StreamReader
while (linesPerPage > count && (( line = reader.ReadLine ()) != null))
{
//Calculate the starting position
yPos = topMargin + (count * verdana10Font.GetHeight (g));
//Draw text
g.DrawString (line, verdana10Font, Brushes.Black, leftMargin, yPos, new StringFormat());
//Move to next line
count++;
}
//If PrintPageEventArgs has more pages to print
if (line != null)
{
ppeArgs.HasMorePages = true;
}
else
{
ppeArgs.HasMorePages = false;
}
}
Step 4.
Now build and run the application. Click Browse button and open a text file and click Print button to print the file contents.


Read more!!!

Monday, February 22, 2010

Printing windows form in C#

Introduction

Vb.net has a PrintForm method but C# does not have inbuilt method for printing a windows form.The following procedure enables us to print a windows form at runtime in c#.net.The base concept involves the capture of the screen image of the windows form in jpeg format during runtime and printing the same on a event like Print button click.

Open a new windows form project and add a new windows form. Include simple controls(label,textbox,button) on the form.From the toolbox,include PrintDialog,PrintDocument components in the form.


In the code behind

Include the following namespaces
using System.Drawing.Imaging;
using System.Drawing.Printing;
and import the following .dll for the necessary GDI functions
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
The following code is placed in the declaration section of the form. The BitBlt function performs a bit-block transfer of the color data corresponding to a rectangle of pixels from the specified source device context into a destination device context.
private System.IO.Stream streamToPrint;
string streamType;
private static extern bool BitBlt
(
IntPtr hdcDest, // handle to destination DC
int nXDest, // x-coord of destination upper-left corner
int nYDest, // y-coord of destination upper-left corner
int nWidth, // width of destination rectangle
int nHeight, // height of destination rectangle
IntPtr hdcSrc, // handle to source DC
int nXSrc, // x-coordinate of source upper-left corner
int nYSrc, // y-coordinate of source upper-left corner
System.Int32 dwRop // raster operation code
);
Select the PrintPage event of the PrintDocument component and include the following code in the event
private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs  e)
{
System.Drawing.Image image = System.Drawing.Image.FromStream
this.streamToPrint;
int x = e.MarginBounds.X;
int y = e.MarginBounds.Y;
int width = image.Width;
int height = image.Height;
if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
{
width = e.MarginBounds.Width;
height = image.Height * e.MarginBounds.Width / image.Width;
}
else
{
height = e.MarginBounds.Height;
width = image.Width * e.MarginBounds.Height / image.Height;
}
System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, width, height);
e.Graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
}
Include the following code in the Print Click event handler
private void btnPrint_Click(object sender, EventArgs e)
{
Graphics g1 = this.CreateGraphics();
Image MyImage = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, g1);
Graphics g2 = Graphics.FromImage(MyImage);
IntPtr dc1 = g1.GetHdc();
IntPtr dc2 = g2.GetHdc();
BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
g1.ReleaseHdc(dc1);
g2.ReleaseHdc(dc2);
MyImage.Save(@"c:\PrintPage.jpg", ImageFormat.Jpeg);
FileStream fileStream = new FileStream(@"c:\PrintPage.jpg", FileMode.Open, FileAccess.Read);
StartPrint(fileStream, "Image");
fileStream.Close();
if (System.IO.File.Exists(@"c:\PrintPage.jpg"))
{
System.IO.File.Delete(@"c:\PrintPage.jpg");
}
}
And the StatrtPrint method to customize the PrintDialog and print the stored image
public void StartPrint(Stream streamToPrint, string streamType)
{
this.printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);
this.streamToPrint = streamToPrint;
this.streamType = streamType;
System.Windows.Forms.PrintDialog PrintDialog1 = new PrintDialog();
PrintDialog1.AllowSomePages = true;
PrintDialog1.ShowHelp = true;
PrintDialog1.Document = printDoc;
DialogResult result = PrintDialog1.ShowDialog();
if (result == DialogResult.OK)
{
printDoc.Print();
//docToPrint.Print();
}
}

The captured image is saved in jpeg format in the defined location.When the print functionality is used throughout an application and the image is not required to be stored, the existing image file is deleted and the new one created is streamed to print.If the image is required to be stored, the filename can be specified at runtime and stored in the given path.

On running the application,the form is displayed as in the image below


On click of the Print button, the Print dialog is displayed.


Read more!!!

Thursday, February 11, 2010

How to keep a form always on top in C#


public void MakeOnTop(Form myTopForm)
{
myTopForm.TopMost = true;
}


Read more!!!