如何在程序中禁止Windows的某个网卡?


在“资源管理器”中的“网络连接”中,可以在某个网卡的右键菜单中选择“停用”来禁止某个网卡,要是要在程序中实现该如何做?

网络编程 VC windows

真·异教徒 12 years, 8 months ago
   
  #include <windows.h>
  
#include <setupapi.h>
#pragma comment( lib,"ws2_32.lib" )
#pragma comment( lib,"setupapi.lib" )

BOOL DisableNetCard(bool bStatus, char szNetName[], char szNetType[])
{
IN LPTSTR DeviceDesc;
DeviceDesc=szNetName;
DWORD NewState;
if(bStatus)
{
NewState=DICS_DISABLE;//禁用
}
else
{
NewState=DICS_ENABLE;//启用
}

//调用ddk函数,来禁用网卡

DWORD i,err;
BOOL Found=false;

HDEVINFO hDevInfo;
SP_DEVINFO_DATA spDevInfoData;

//访问系统的硬件库
//DIGCF_PRESENT
//"PCMCIA"
// hDevInfo=SetupDiGetClassDevs(NULL,"PCI",NULL,DIGCF_ALLCLASSES );
hDevInfo=SetupDiGetClassDevs(NULL,szNetType,NULL,DIGCF_ALLCLASSES );
if (hDevInfo == INVALID_HANDLE_VALUE)
{

}

//枚举硬件,获得需要的接口
spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i=0;SetupDiEnumDeviceInfo(hDevInfo,i,&spDevInfoData;);i++)
{
DWORD DataT;
LPTSTR p,buffer = NULL;
DWORD buffersize = 0;

//获得硬件的属性值

//SPDRP_DEVICEDESC:根据设备名称
//SPDRP_HARDWAREID:根据硬件设备Component ID
//
while (!SetupDiGetDeviceRegistryProperty(
hDevInfo,
&spDevInfoData;,
SPDRP_DEVICEDESC,
&DataT;,
(PBYTE)buffer,
buffersize,
&buffersize;))
{
if (GetLastError() == ERROR_INVALID_DATA)
{
//不存在device desc. Continue.
break;
}
else if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
//buffer size不对.
if (buffer)
LocalFree(buffer);
buffer =(char *) LocalAlloc(LPTR,buffersize);
}
else
{
//未知错误
goto cleanup_DeviceInfo;
}
}

if (GetLastError() == ERROR_INVALID_DATA)
continue;

//比较,找到和配置设备相同的项
for (p=buffer;*p&&(p<&buffer;[buffersize]);p+=lstrlen(p)+sizeof(TCHAR))
{

// if (!_tcscmp(HardwareId,p))
if (!_tcscmp(DeviceDesc,p))
{
//找到网卡
Found = TRUE;
break;
}
}

if (buffer)
LocalFree(buffer);

//如果相等
if (Found)
{
//禁用该设备

SP_PROPCHANGE_PARAMS spPropChangeParams;

spPropChangeParams.ClassInstallHeader.cbSize=sizeof(SP_CLASSINSTALL_HEADER);
spPropChangeParams.ClassInstallHeader.InstallFunction=DIF_PROPERTYCHANGE;
spPropChangeParams.Scope=DICS_FLAG_GLOBAL;
spPropChangeParams.StateChange=NewState;//禁用:DICS_DISABLE,DICS_ENABLE启用

//
if(!SetupDiSetClassInstallParams(hDevInfo,&spDevInfoData;,(SP_CLASSINSTALL_HEADER *)&spPropChangeParams;,sizeof(spPropChangeParams)))
{
DWORD errorcode=GetLastError();
}

if(!SetupDiCallClassInstaller(DIF_PROPERTYCHANGE,hDevInfo,&spDevInfoData;))
{
DWORD errorcode=GetLastError();
}

switch(NewState)
{
case DICS_DISABLE:
AfxMessageBox("成功禁用网络!");
break;
case DICS_ENABLE:
AfxMessageBox("成功启用网络!");
break;
}

break;
}

}

//退出时,清理工作环境
cleanup_DeviceInfo:
err = GetLastError();
SetupDiDestroyDeviceInfoList(hDevInfo);
SetLastError(err);
}

测试代码 DisableNetCard(true,"Atheros AR8132 PCI-E Fast Ethernet Controller","PCI")
经测试可以用,不足的是要先知道网卡类型和网卡名称,不过可以再加一个函数得到网卡的属性信息。

薔薇殺しD鸑鷟 answered 12 years, 8 months ago

Your Answer