본문 바로가기
삽질/Delphi

[Delphi] 기본 프린터 설정 및 정보 가져오기

by 푸딩s 2020. 5. 28.

type
 TPrinterInfo = record
  SeverName: PChar;
  PrinterName: PChar;
  ShareName: PChar;
  PortName: PChar;
  DriverName: PChar;
  Comment: PChar;
  Location: PChar;
  DeviceMode: PDeviceModeW;
  SepFile: PChar;
  PrintProcessor: PChar;
  DataType: PChar;
  Parameters: PChar;
  SecurityDescriptor: PSecurityDescriptor;
  Attributes: Cardinal;
  DefaultPriority: Cardinal;
  StartTime: Cardinal;
  UntilTime: Cardinal;
  Status: Cardinal;
  Jobs: Cardinal;
  AveragePPM: Cardinal;
 end;

function GetCurPrinterInfo: TPrinterInfo;
 function GetCurrentPrinterHandle: THandle;
 var
  Device, Driver, Port: array [0 .. 255] of char;
  hDeviceMode: THandle;
 begin
  Printer.GetPrinter(Device, Driver, Port, hDeviceMode);
  if not OpenPrinter(@Device, Result, nil) then
   RaiseLastWin32Error;
 end;

var
 hPrinter: THandle;
 pInfo: PPrinterInfo2;
 bytesNeeded: DWORD;
begin
 hPrinter := GetCurrentPrinterHandle;
 try
  WinSpool.GetPrinter(hPrinter, 2, Nil, 0, @bytesNeeded);
  pInfo := AllocMem(bytesNeeded);
  try
   WinSpool.GetPrinter(hPrinter, 2, pInfo, bytesNeeded, @bytesNeeded);
   Result.SeverName := pInfo^.pServerName;
   Result.PrinterName := pInfo^.pPrinterName;
   Result.ShareName := pInfo^.pShareName;
   Result.PortName := pInfo^.pPortName;
   Result.DriverName := pInfo^.pDriverName;
   Result.Comment := pInfo^.pComment;
   Result.Location := pInfo^.pLocation;
   Result.DeviceMode := pInfo^.pDevMode;
   Result.SepFile := pInfo^.pSepFile;
   Result.PrintProcessor := pInfo^.pPrintProcessor;
   Result.DataType := pInfo^.pDatatype;
   Result.Parameters := pInfo^.pParameters;
   Result.SecurityDescriptor := pInfo^.PSecurityDescriptor;
   Result.Attributes := pInfo^.Attributes;
   Result.DefaultPriority := pInfo^.DefaultPriority;
   Result.StartTime := pInfo^.StartTime;
   Result.UntilTime := pInfo^.UntilTime;
   Result.Status := pInfo^.Status;
   Result.Jobs := pInfo^.cJobs;
   Result.AveragePPM := pInfo^.AveragePPM;
  finally
   FreeMem(pInfo);
  end;
 finally
  ClosePrinter(hPrinter);
 end;
end;

function GetDefaultPrinter: string;
var
 ResStr: array [0 .. 255] of char;
begin
 GetProfileString('Windows', 'device', '', ResStr, 255);
 Result := StrPas(ResStr);
end;

procedure SetDefaultPrinter(NewDefPrinter: string);
var
 ResStr: array [0 .. 255] of char;
begin
 StrPCopy(ResStr, NewDefPrinter);
 WriteProfileString('windows', 'device', ResStr);
 StrCopy(ResStr, 'windows');
 PostMessage(HWND_BROADCAST, WM_WININICHANGE, 0, Longint(@ResStr));
end;

댓글