1. Home
  2. Computing & Technology
  3. Delphi Programming

How to Change the Default Windows Printer from Code

By Zarko Gajic, About.com

Here's how to change the default Windows printer if you know the printer's name:

~~~~~~~~~~~~~~~~~~~~~~~~~
uses WinSpool, ... ;

procedure ChangeDefaultPrinter(const Name: string) ;
var
    W2KSDP: function(pszPrinter: PChar): Boolean; stdcall;
    H: THandle;
    Size, Dummy: Cardinal;
    PI: PPrinterInfo2;
begin
    if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion >= 5) then
    begin
      @W2KSDP := GetProcAddress(GetModuleHandle(winspl), 'SetDefaultPrinterA') ;
      if @W2KSDP = nil then RaiseLastOSError;
      if not W2KSDP(PChar(Name)) then RaiseLastOSError;
    end
    else
    begin
      if not OpenPrinter(PChar(Name), H, nil) then RaiseLastOSError;
      try
        GetPrinter(H, 2, nil, 0, @Size) ;
        if GetLastError <> ERROR_INSUFFICIENT_BUFFER then RaiseLastOSError;
        GetMem(PI, Size) ;
        try
          if not GetPrinter(H, 2, PI, Size, @Dummy) then RaiseLastOSError;
          PI^.Attributes := PI^.Attributes or PRINTER_ATTRIBUTE_DEFAULT;
          if not SetPrinter(H, 2, PI, PRINTER_CONTROL_SET_STATUS) then RaiseLastOSError;
        finally
          FreeMem(PI) ;
        end;
      finally
        ClosePrinter(H) ;
      end;
    end;
end; //ChangeDefaultPrinter
~~~~~~~~~~~~~~~~~~~~~~~~~

Note: Using Delphi's global Printer variable (of type TPrinter) you can fill a ComboBox with all available printers:

  cboPrinters.Items.Assign(Printer.Printers) ;

Then, when a user clicks some button (for example) call the ChangeDefaultPrinter procedure:

  if cboPrinters.ItemIndex = -1 then Exit;
  ChangeDefaultPrinter(cboPrinters.Items[cboPrinters.ItemIndex]) ;

Delphi tips navigator:
» How to Break a Long Menu into Columns
« How to remember Delphi form controls position and size

More Delphi Programming Quick Tips
Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2005 Delphi Tips
  7. How to change the default Windows printer from Delphi code

©2009 About.com, a part of The New York Times Company.

All rights reserved.