Mirror

How to stop and delete all print jobs through code (Views: 100)


Problem/Question/Abstract:

I can stop and delete current printing jobs from the "Printer Manager". Can I do it in my code, too? I want to stop all print jobs and delete them in my program.

Answer:

Try the PurgeJobsOnCurrentPrinter procedure given below. Not tested!

uses
  winspool, printers;

{GetCurrentPrinterHandle:
Retrieves the handle of the current printer and returns an API printer handle for the
current printer. Uses WinSpool.OpenPrinter to get a printer handle. The caller takes
ownership of the handle and must call ClosePrinter on it once the handle is no longer
needed. Failing to do that creates a serious resource leak! Raises EWin32Error if the
OpenPrinter call fails.}

function GetCurrentPrinterHandle: THandle;
const
  Defaults: TPrinterDefaults = (pDatatype: nil; pDevMode: nil; DesiredAccess:
    PRINTER_ACCESS_USE or PRINTER_ACCESS_ADMINISTER);
var
  Device, Driver, Port: array[0..255] of char;
  hDeviceMode: THandle;
begin
  Printer.GetPrinter(Device, Driver, Port, hDeviceMode);
  if not OpenPrinter(@Device, Result, @Defaults) then
    RaiseLastWin32Error;
end;

{Kill all pending jobs on the current printer}

procedure PurgeJobsOnCurrentPrinter;
var
  hPrinter: THandle;
begin
  hPrinter := GetCurrentPrinterHandle;
  try
    if not WinSpool.SetPrinter(hPrinter, 0, nil, PRINTER_CONTROL_PURGE) then
      RaiseLastWin32Error;
  finally
    ClosePrinter(hPrinter);
  end;
end;

<< Back to main page