Tuesday, July 8, 2008

How to set a default printer for your application

Here i use an ini file to store my printer index.

1st, I use these components:

Dialogs ----> TPrinterSetupDialog;
Printers ----> TPrinter
IniFiles----> TIniFile


Then here is the form startup and close. PrinterIndex is just a global variable.

procedure TForm1.FormCreate(Sender: TObject);
var
IniFile : TIniFile;
begin
IniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'configuration.ini');
// Read the value from the ini file
PrinterIndex := IniFile.ReadInteger('Printer','Index',0);
IniFile.Free;
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
var
IniFile : TIniFile;
begin
IniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'configuration.ini');
// Save the value into the ini file
IniFile.WriteInteger('Printer','Index',PrinterIndex);
IniFile.Free;
end;


So in your application you can do it this:

procedure TForm1.Button1Click(Sender: TObject);
begin
// Change current printer index to the value we get from the ini file.
Printer.PrinterIndex := PrinterIndex;
ShowMessage(IntToStr(Printer.PrinterIndex));

// Open the dialog
PrinterSetupDialog1.Execute;

// Set new value to the PrinterIndex variable.
ShowMessage(IntToStr(Printer.PrinterIndex));
PrinterIndex := Printer.PrinterIndex;
...
...

No comments: