Mega Code Archive

 
Categories / Delphi / Printing
 

Setting the default printer

Title: Setting the default printer Question: How can I set the default Windows printer from code? Answer: The following example shows how to retrieve the available printers and display them in a ListBox, and then how to set the selected printer as the default printer: type TDevice = record Name, Driver, Port: string; end; var Devices: array of TDevice; DDevice: TDevice; // current default printer procedure TForm1.FormCreate(Sender: TObject); var WinIni: TIniFile; DevList: TStringList; device: string; i, p: integer; begin WinIni := TIniFile.Create('WIN.INI'); // Get the current default printer device := WinIni.ReadString('windows', 'device', ',,'); if device = '' then device := ',,'; p := Pos(',', device); DDevice.Name := Copy(device, 1, p-1); device := Copy(device, p+1, Length(device)-p); p := Pos(',', device); DDevice.Driver := Copy(device, 1, p-1); DDevice.Port := Copy(device, p+1, Length(device)-p); // Get the printers list DevList := TStringList.Create; WinIni.ReadSectionValues('Devices', DevList); // Store the printers list in a dynamic array SetLength(Devices, DevList.Count); for i := 0 to DevList.Count - 1 do begin device := DevList[i]; p := Pos('=', device); Devices[i].Name := Copy(device, 1, p-1); device := Copy(device, p+1, Length(device)-p); p := Pos(',', device); Devices[i].Driver := Copy(device, 1, p-1); Devices[i].Port := Copy(device, p+1, Length(device)-p); // Add the printer to the ListBox ListBox1.Items.Add(Devices[i].Name + ' (' + Devices[i].Port + ')'); // Is the current default printer? if (CompareText(Devices[i].Name, DDevice.Name) = 0) and (CompareText(Devices[i].Driver, DDevice.Driver) = 0) and (CompareText(Devices[i].Port, DDevice.Port) = 0) then ListBox1.ItemIndex := i; // Make it the selected printer end; WinIni.Free; end; procedure TForm1.Button1Click(Sender: TObject); var WinIni: TIniFile; begin if ListBox1.ItemIndex = -1 then exit; DDevice := Devices[ListBox1.ItemIndex]; WinIni := TIniFile.Create('WIN.INI'); WinIni.WriteString('windows', 'device', DDevice.Name + ',' + DDevice.Driver + ',' + DDevice.Port); WinIni.Free; SendMessage(HWND_BROADCAST, WM_WININICHANGE, 0, LPARAM(pchar('windows'))); end; procedure TForm1.ListBox1DblClick(Sender: TObject); begin Button1Click(Sender); end;