List local printers

为君一笑 提交于 2019-12-10 10:43:34

问题


I am using this routine to list the local printers installed on on a machine:

var
  p: pointer;
  hpi: _PRINTER_INFO_2A;
  hGlobal: cardinal;
  dwNeeded, dwReturned: DWORD;
  bFlag: boolean;
  i: dword;
begin
  p := nil;
  EnumPrinters(PRINTER_ENUM_LOCAL, nil, 2, p, 0, dwNeeded, dwReturned);
  if (dwNeeded = 0) then exit;
  GetMem(p,dwNeeded);
  if (p = nil) then exit;
  bFlag := EnumPrinters(PRINTER_ENUM_LOCAL, nil, 2, p, dwneeded, dwNeeded, dwReturned);
  if (not bFlag) then exit;
  CbLblPrinterPath.Properties.Items.Clear;
  for i := 0 to dwReturned - 1 do
  begin
    CbLblPrinterPath.Properties.Items.Add(TPrinterInfos(p^)[i].pPrinterName);
  end;
  FreeMem(p);

TPrinterInfos(p^)[i].pPrinterName returns a 'P' for printer name. I have a PdfCreator installed as a printer.

TPrinterInfos is an array of _PRINTER_INFO_2A.

How can i fix this?


回答1:


Ok, first thing first... Since you tagged this Delphi-2010, I'd assume you are having this problem with D2010.

Your problem start with your use of _PRINTER_INFO_2A, which is the structure used by the Ansi version of the function EnumPrinters. Ever since unicode has been introduced, the "EnumPrinters" function maps to the unicode version of the function, and thus, you should use _PRINTER_INFO_2W. (Or explicitly call EnumPrintersA). If you are using EnumPrinters(Without A/W) you should use the _PRINTER_INFO_2(without A/W). That way, it will be less likely to break if one day a UTF32 version becomes the new standard.




回答2:


You can get a list of Local Printers by Simply using the list provided in the Printer variable. Simple as

uses Printers;
...
procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.Lines.Assign(Printer.Printers);
end;

I would use this method unless you have a specific reason for doing what you are doing.

More recently I have created a github repo with a utility that does this.

github.com/tobya/listprn




回答3:


Since you are using unicode Delphi version you should use _PRINTER_INFO_2W structure instead of _PRINTER_INFO_2A



来源:https://stackoverflow.com/questions/2601037/list-local-printers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!