完整的网络资源枚举函数:
可以根据需要选择资源类型,稍加改动即可生成网络资源树。
function EnumerateNetRes(ParentRes: PNetResource; NetResList: TStrings):boolean;
type
PNetResourceArray = ^TNetResourceArray;
TNetResourceArray = array[0..MaxInt div SizeOf(TNetResource) - 1] of TNetResource;
var
NetResources: PNetResourceArray;
NetResource: TNetResource;
NetHandle: THandle;
Count, BufSize, NetResult, Size, i: DWORD;
NeedEnum: boolean;
tName: string;
begin
Result := false;
NetResult := WNetOpenEnum( RESOURCE_GLOBALNET, // all network resource
RESOURCETYPE_ANY, // all resource
0, // enumerate all resource
ParentRes, //
NetHandle); // handle to the resource
if NetResult <> NO_ERROR then
exit;
try
BufSize := 50 * SizeOf(TNetResource);
GetMem(NetResources, BufSize);
try
repeat
Count := $FFFFFFFF;
Size := BufSize;
// 取网络资源
NetResult := WNetEnumResource(NetHandle,
Count, // define locally
NetResources, //
Size); //获取网络类型信息
if NetResult = ERROR_MORE_DATA then
begin
BufSize := Size;
ReallocMem(NetResources, BufSize);
Continue;
end;
if NetResult <> NO_ERROR then Exit;
NeedEnum := true;
for I := 0 to Count - 1 do
begin
with NetResources do
begin
case dwDisplayType of
1: tName := '工作组';
2: tName := '计算机';
3: if dwType = 2 then
tName := '打印机'
else
tName := '文件夹';
6: tName := '全局';
else
tName := '未知资源';
end;
NetResList.Add( tName + ':' + lpRemoteName);
end;
application.ProcessMessages;
if NeedEnum and ((NetResources.dwUsage and RESOURCEUSAGE_CONTAINER) = RESOURCEUSAGE_CONTAINER) then
begin
NetResource := NetResources;
// 搜索下一级资源
EnumerateNetRes( PNetResource(@NetResource), NetResList );
end;
end;
until NetResult <> ERROR_NO_MORE_ITEMS;
finally
FreeMem(NetResources, BufSize);
end;
finally
WNetCloseEnum(NetHandle);
end;
Result := true;
end;
向ListBox添加网络资源的例子。
procedure TForm1.Button2Click(Sender: TObject);
begin
ListBox1.Items.Clear;
EnumerateNetRes( nil, ListBox1.Items );
ListBox1.Items.Add('--End of net browsing--');
end;