Title: Adding a printer
Question: How to add a printer by code?
Answer:
In order to add a printer by code, we must use the Win API call AddPrinter, which takes three parameters:
1) the name of the printer
2) the printing level
3) the printer description
The following code provides a wrapper for this function. All you have to do is supply the Name of the printer as you want it to appear in Windows Explorer, the name of the port the printer is attached to (e.g. LPT1:), the name of the driver (you have to look this up by hand) and the name of the print processor (which is normally "winprint"). The code takes care of calling the API function.
unit unit_AddPrinter;
interface
function AddAPrinter(PrinterName, PortName, DriverName, PrintProcessor: string): boolean;
implementation
uses
SysUtils,
WinSpool,
Windows;
function AddAPrinter(PrinterName, PortName, DriverName, PrintProcessor: string): boolean;
var
pName: PChar;
Level: DWORD;
pPrinter: PPrinterInfo2;
begin
pName := nil;
Level := 2;
New(pPrinter);
pPrinter^.pServerName := nil;
pPrinter^.pShareName := nil;
pPrinter^.pComment := nil;
pPrinter^.pLocation := nil;
pPrinter^.pDevMode := nil;
pPrinter^.pSepFile := nil;
pPrinter^.pDatatype := nil;
pPrinter^.pParameters := nil;
pPrinter^.pSecurityDescriptor := nil;
pPrinter^.Attributes := 0;
pPrinter^.Priority := 0;
pPrinter^.DefaultPriority := 0;
pPrinter^.StartTime := 0;
pPrinter^.UntilTime := 0;
pPrinter^.Status := 0;
pPrinter^.cJobs := 0;
pPrinter^.AveragePPM :=0;
pPrinter^.pPrinterName := PCHAR(PrinterName);
pPrinter^.pPortName := PCHAR(PortName);
pPrinter^.pDriverName := PCHAR(DriverName);
pPrinter^.pPrintProcessor := PCHAR(PrintProcessor);
if AddPrinter(pName, Level, pPrinter) 0 then
Result := true
else begin
// ShowMessage(inttostr(GetlastError));
Result := false;
end;
end;
end.