Skip to content

Instantly share code, notes, and snippets.

@DelphiWorlds
Last active January 21, 2019 03:40
Show Gist options
  • Save DelphiWorlds/88643af51f50f86c8183ab8c31bc12d0 to your computer and use it in GitHub Desktop.
Save DelphiWorlds/88643af51f50f86c8183ab8c31bc12d0 to your computer and use it in GitHub Desktop.
Enumerating network printers in Windows
type
TNetResourceArray = TArray<TNetResource>;
function EnumerateContainedPrinters(const AContainer: TNetResource): TNetResourceArray;
var
LResult, LBufferSize: DWORD;
LEnumHandle: THandle;
LNetResources: TNetResourceArray;
I: Integer;
LEntries : Longint;
begin
LEntries := -1;
LBufferSize := 16384;
LResult := WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_PRINT, RESOURCEUSAGE_CONNECTABLE, @AContainer, LEnumHandle);
if LResult = NO_ERROR then
try
SetLength(LNetResources, LBufferSize div SizeOf(TNetResource));
LResult := WNetEnumResource(LEnumHandle, DWORD(LEntries), @LNetResources[0], LBufferSize);
SetLength(Result, LEntries);
for I := 0 to LEntries - 1 do
Result[I] := LNetResources[I];
finally
WNetCloseEnum(LEnumHandle);
end;
end;
function EnumeratePrinters: TNetResourceArray;
var
LResult, LBufferSize: DWORD;
LEnumHandle: THandle;
LNetResources, LPrinters: TNetResourceArray;
I: Integer;
LEntries : Longint;
begin
LEntries := -1;
LBufferSize := 16384;
LResult := WNetOpenEnum(RESOURCE_CONTEXT, RESOURCETYPE_PRINT, 0, nil, LEnumHandle);
if LResult = NO_ERROR then
try
SetLength(LNetResources, LBufferSize div SizeOf(TNetResource));
LResult := WNetEnumResource(LEnumHandle, DWORD(LEntries), @LNetResources[0], LBufferSize);
for I := 0 to LEntries - 1 do
begin
if (LNetResources[I].dwUsage = RESOURCEUSAGE_CONTAINER) and (LNetResources[I].dwType = RESOURCETYPE_PRINT) then
Result := Concat(Result, EnumerateContainedPrinters(LNetResources[I]));
end;
finally
WNetCloseEnum(LEnumHandle);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
LPrinter: TNetResource;
begin
for LPrinter in EnumeratePrinters do
begin
if LPrinter.dwType = 2 then
ListBox1.Items.Add(Format('%s (%s)', [LPrinter.lpComment, LPrinter.lpRemoteName]));
end;
end;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment