Custom Search

Thursday, January 31, 2008

Start a process in c#

With this code you can start the process mshearts.exe when a user uses the click event.

All you have to do is create a new process and specify the location of it. Then the start event is called and the process will pop up.

private void button2_Click(object sender, EventArgs e)


Process proc = new Process();

proc.StartInfo = new ProcessStartInfo(@"C:\Windows\system32\mshearts.exe");



Wednesday, January 23, 2008

Useful Creation Pattern: Singleton Design Pattern.

This pattern want to make sure that there will be only one instance of the class and you provide access to it. For this we make the default constructor private and also we create a static object of Singleton that we initialize in the method getInstance() or we return it if it has been already initialized.

public class Singleton


private Singleton(){}

private static Singleton instance;

public static Singleton getInstance()


if (instance == null)


instance = new Singleton();


return instance;



Monday, January 21, 2008

Adding information to the Print Page

This c# code lets you add an image to the print page.

using System;

using System.Collections;

using System.ComponentModel;

using System.Drawing;

using System.Drawing.Printing;

using System.Data;

using System.Windows.Forms;

Graphics g = e.Graphics;

g.PageUnit = GraphicsUnit.Millimeter;

System.Drawing.Image logo;

//Here you have to specify the location of the image

logo = System.Drawing.Image.FromFile("logo.gif");

//Locate the logo image on the location set on new Point

g.DrawImage(logo, new Point(155, 5));

Adding some text to the page:

String text = "Text to be added";

//You can set the font, type, location and many other features.

Font fontText = new Font("Times New Roman", 12, FontStyle.Regular);

g.DrawString(text , fontText, Brushes.Black , new Point(54, 4));

Drawing a line:

Pen pen= new Pen(Color.Gray);

//Set the begin and the end of the line.

e.DrawLine(pen,new Point(x1,y1),new Point(x2,y2));

Wednesday, January 16, 2008

Print Preview in c#

This code is to show the document printDoc on the Print Preview window.

PrintPreviewDialog dlg = new PrintPreviewDialog();

printDoc.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);

//Assign printDoc as the document to preview

dlg.Document = printDoc;


Print in c#

This is a c# code that opens the Windows Print Dialog and lets you choose the printer you want from the list.

PrintDialog dia = new PrintDialog();

printDoc.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);

if (dia.ShowDialog() == DialogResult.OK)


printDoc.PrinterSettings.PrinterName = dia.PrinterSettings.PrinterName;