标签:open net img tco port guid out ext fun
1.关闭wifi ,调用Api
[DllImport("Wlanapi.dll", SetLastError = true)] public static extern uint WlanDisconnect(IntPtr hClientHandle, ref Guid pInterfaceGuid, IntPtr pReserved);
2.获取当前连接wifi 网卡句柄
The WlanOpenHandle function opens a connection to the server.
就是为了返回 ClientHandle ,传入WlanDisconnect(...) 中的hClientHandle 的参数。
官方解释【A handle for the client to use in this session. This handle is used by other functions throughout the session.】
[DllImport("Wlanapi.dll")] private static extern int WlanOpenHandle(uint dwClientVersion, IntPtr pReserved, [Out]out uint pdwNegotiatedVersion, out IntPtr ClientHandle);
3.WlanDisconnect(...)中还有一个参数pInterfaceGuid要获取,就是真实网卡(安装了虚拟机要虚拟网卡)的唯一标识符,无线和有线还不一样。
3.1 真实网卡可以通过Win32_NetworkAdapter(可以查询此类的属性,其中有【GUID】) 获取,因为真实网卡的 PNPDeviceID 都是【PCI】开头
SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionStatus=2 AND PNPDeviceID LIKE ‘PCI%‘");
以上 获取了已连接的真实网卡,笔记本一般有无线和有线网卡,如果无线和有线都连接,获取了两条记录,NetConnectionStatus 条件是连接状态 【2】:已连接,【7】:未连接。
3.2通过Win32_NetworkAdapter我们可以获取 真实网卡的唯一标识符 GUID. 区别有线还是无线,我们可以通过注册表判断注册表路径:HKLM\SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\【GUID】\Connection
路径下的键值 MediaSubType,如果Value=2,表示无线网卡。
4. 最终形成
public static bool Disconnect() { IntPtr _clientHandle = IntPtr.Zero; uint negotiatedVersion; int code = WlanOpenHandle(1, IntPtr.Zero, out negotiatedVersion, out _clientHandle); NetworkInterface[] _interface = NetworkInterface.GetAllNetworkInterfaces(); ManagementObjectSearcher searcher = new ManagementObjectSearcher( @"SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionStatus=2 AND PNPDeviceID LIKE ‘PCI%‘"); string GUID = ""; foreach (ManagementObject mo in searcher.Get()) { GUID = mo["GUID"].ToString().Trim(); Console.WriteLine(GUID); var registryKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\" + GUID + "\\Connection", false); if (registryKey != null) { var mediaSubTypevalue = registryKey.GetValue("MediaSubType"); if (mediaSubTypevalue != null) { int num; int.TryParse(mediaSubTypevalue.ToString(), out num); if (num == 2) { Guid netIfaceGuid = new Guid(GUID); var ERROR_SUCCESS = WlanDisconnect(_clientHandle, ref netIfaceGuid, IntPtr.Zero); if (ERROR_SUCCESS == 0) { return true; } WlanCloseHandle(_clientHandle, IntPtr.Zero);//不确定 } } } } return false; }
5.后记
我用的是NativeWifi 类库,进行打开wifi的,NativeWifi 也是封装了windows 的Wlanapi.dll 的方法。但是没有关闭连接wifi方法,所以只能自己写。
文章参考:
关闭Windows 系统当前连接的Wifi以及判断物理\虚拟网卡,有线\无线网卡
标签:open net img tco port guid out ext fun
原文地址:https://www.cnblogs.com/aguan/p/8945136.html