AdapterList
本文档解释了如何在 C# 中使用 DDK 接口 INetCfg。
引言
NetCfgTest 使用 DDK 接口 INetCfg
及其相关接口来获取系统上安装的网络适配器列表。本文档描述了
- 如何为纯 COM 接口编写互操作代码。
- 如何使用 C# 中的
INetCfg
获取已安装的网络适配器。 - 如何从 C# 初始化纯 COM 类。
背景
有一个需求是在 C# 中使用接口 INetCfg
。我努力为这个接口获取 COM 互操作性。最终,我决定自己编写一个。
Using the Code
接口 INetCfg
编写在 NetCfg
命名空间中。我们可以使用以下源代码来获取适配器列表。
object objINetCfg = null;
int nRet = 0;
nRet = Ole32Methods.CoCreateInstance(ref INetCfg_Guid.CLSID_CNetCfg, null,
Ole32Methods.CLSCTX_INPROC_SERVER, ref INetCfg_Guid.IID_INetCfg, out objINetCfg);
INetCfg netCfg = objINetCfg as INetCfg;
nRet = netCfg.Initialize(IntPtr.Zero);
object componet = new object();
nRet = netCfg.QueryNetCfgClass(ref INetCfg_Guid.IID_DevClassNet,
ref INetCfg_Guid.IID_INetCfgClass, out componet);
INetCfgClass NetCfgClass = componet as INetCfgClass;
object EnumNetCfgComponentObj = new object();
nRet = NetCfgClass.EnumComponents(out EnumNetCfgComponentObj);
IEnumNetCfgComponent EnumNetCfgComponent =
EnumNetCfgComponentObj as IEnumNetCfgComponent;
EnumNetCfgComponent.Reset();
object netCfgCompObj = new object();
INetCfgComponent netcfgcomp = null;
int outCelt = 0;
nRet = EnumNetCfgComponent.Next(1, out netCfgCompObj, out outCelt);
netcfgcomp = netCfgCompObj as INetCfgComponent;
string strBind;
string strDispName = "";
do
{
netcfgcomp.GetBindName(out strBind);
netcfgcomp.GetDisplayName(out strDispName);
System.Runtime.InteropServices.Marshal.ReleaseComObject(netcfgcomp);
netCfgCompObj = null;
this.listBox1.Items.Add(strDispName+" - " + strBind);
nRet = EnumNetCfgComponent.Next(1, out netCfgCompObj, out outCelt);
netcfgcomp = netCfgCompObj as INetCfgComponent;
GC.Collect();
} while (nRet == 0);
System.Runtime.InteropServices.Marshal.ReleaseComObject(EnumNetCfgComponent);
EnumNetCfgComponent = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(objINetCfg);
objINetCfg = null;
GC.Collect();
关注点
我第一次为纯 COM 接口编写互操作代码。学习如何在 C# 中使用纯 COM 接口的细节,这真的很有趣。
历史
- 2008 年 9 月 26 日:创建版本 1.0。