Search code examples
windowsdelphidelphi-2010

How to solve TPrintDialog not saving settings?


I'm using TPrintDialog in an application, before printing, I prompt the user with the dialog, the user changes whatever settings s/he wants and then clicks OK.

The trouble is, when the application is closed and relaunched, the page size is not the same as previously selected(Letter) but set to A4 -- is this a windows issue? this happens on Windows XP SP3(32bit), on Windows 7 Ultimate(64bit) the reverse happens, by default, page size "Letter" is selected and if the user selects A4 and closes the application, relaunch, "Letter" is selected.


Solution

  • The OS does nothing to persist printer settings for applications, it only keeps default settings. Likewise, the VCL shows no effort on this regard. The first time a printer is needed after the application is launched, it retrieves the default settings for that particular printer. So you need to implement your way of saving and applying settings.

    Here's some simple code that would set the paper type to 'Letter' before showing the print dialog:

    var
      Device: array[0..540] of Char;
      Driver, Port: array[0..1] of Char;
      DevMode: THandle;
      PDevMode: PDeviceMode;
    begin
      Printer.GetPrinter(Device, Driver, Port, DevMode);
      PDevMode := GlobalLock(DevMode);
      PDevMode.dmPaperSize := DMPAPER_LETTER;
      Printer.SetPrinter(Device, Driver, Port, DevMode);
      GlobalUnlock(DevMode);
    
      PrintDialog1.Execute();
    end;
    


    Similarly you can get the paper type or other settings from a DeviceMode structure and save them to registry f.i. while closing the application for later use.