MicroSoft提供了以下几个API:WnetOpenEnum、WnetEnumResource、WNetCloseEnum及一个结构类型NETRESOURCE用于搜索局域网上的网络资源。
其中NETRESOURCE的定义如下:
typedef strUCt _NETRESOURCE { // nr
DWord dwScope;
DWORD dwType;
DWORD dwDisplayType;
DWORD dwUsage;
LPTSTR lpLocalName;
LPTSTR lpRemoteName;
LPTSTR lpComment;
LPTSTR lpProvider;
} NETRESOURCE;
我们主要用到是dwType(资源类型:磁盘或打印机)、dwDisplayType(资源类型:服务器,域等)、dwUsage(判定是不是容器c o ntainer)、lpRemoteName(资源名称)。
WnetOpenEnum的作用是打开某一特定的资源容器句柄给WnetEnumResource。WnetEnumResource枚举出指定容器下所有网络资源。
下面是一个列出所有网络资源的的函数示例:
bool __fastcall TForm1::EnumerateFunc(HWND hwnd ,LPNETRESOURCE lpnr,TTreeNode * ParentNode)
{
DWORD dwResult, dwResultEnum;
HANDLE hEnum;
DWORD cbBuffer = 16384; /* 16K is reasonable size */
DWORD cEntries = 0xFFFFFFFF; /* enumerate all possible entries */
LPNETRESOURCE lpnrLocal; /* pointer to enumerated structures */
DWORD i;
dwResult = WNetOpenEnum(RESOURCE_GLOBALNET,
RESOURCETYPE_ANY,
0, /* enumerate all resources */
lpnr, /* NULL first time this function is called */
&hEnum); /* handle to resource */
if (dwResult ==67) //domain下没有可访问的主机
return true;
if (dwResult != NO_ERROR ) { //无
ShowError(dwResult);
return false;
}
TTreeNode * Child;
do {
lpnrLocal = (LPNETRESOURCE) GlobalAlloc(GPTR, cbBuffer);
dwResultEnum = WNetEnumResource(hEnum, /* resource handle */
&cEntries, /* defined locally as 0xFFFFFFFF */
lpnrLocal, /* LPNETRESOURCE */
&cbBuffer); /* buffer size */
if (dwResultEnum == NO_ERROR) {
for(i = 0; i < cEntries; i++) {
Child=TreeView1->Items->AddChild(ParentNode,lpnrLocal[i].lpRemoteName);
if(RESOURCEUSAGE_c o nTAINER ==
(lpnrLocal[i].dwUsage & RESOURCEUSAGE_c o nTAINER))
if(!EnumerateFunc(this->Handle, &lpnrLocal[i],Child))
ShowMessage("EnumerateFunc returned FALSE.");
}
}
else if (dwResultEnum != ERROR_NO_MORE_ITEMS) {
ShowError(dwResultEnum);
break;
}
}
while(dwResultEnum != ERROR_NO_MORE_ITEMS);
GlobalFree((HGLOBAL) lpnrLocal);
dwResult = WNetCloseEnum(hEnum);
if(dwResult != NO_ERROR) {
ShowError(dwResult);
return FALSE;
}
return true;
}
需要说明在win98下,此方法列出的资源和网络邻居列出的是一样,和网络邻居一样,有时列出的数据并不准确,可能会有一些域或机器不能找到。