SetLastError = true )] public static extern uint WlanDiscon

时间:2021-11-25 02:29:35

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; }

View Code

5.跋文

我用的是NativeWifi 类库,进行打开wifi的,NativeWifi 也是封装了windows 的Wlanapi.dll 的要领。但是没有*连接wifi要领,所以只能本身写。

文章参考:

有线网卡与无线网卡、物理网卡与虚拟网卡的区分

*Windows 系统当前连接的Wifi以及判断物理\虚拟网卡,有线\无线网卡

标签:

原文地点:https://www.cnblogs.com/aguan/p/8945136.html