1.更新MAC地址
将注册表中的键值添加上MAC地址
2.重新连接网络
试过了3个方法:
ManagementClass最新提供了Disable,Enable方法,但只支持Vista操作系统
Shell.dll的方法,可以实现,但处理起来很烦,另外在重新连接时显示“启动中”提示框,不友好。
NetSharingManagerClass 的Disconnect, Connect方法,可以实现,但有一个问题是,会重新更新IP地址,有明显感觉等。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Win32; using System.Net.NetworkInformation; using System.Management; using System.Threading; using System.Runtime.InteropServices; using NETCONLib; namespace DynamicMAC { public class MACHelper { [DllImport("wininet.dll")] private extern static bool InternetGetConnectedState(int Description, int ReservedValue); /// <summary> /// 是否能连接上Internet /// </summary> /// <returns></returns> public bool IsConnectedToInternet() { int Desc = 0; return InternetGetConnectedState(Desc, 0); } /// <summary> /// 获取MAC地址 /// </summary> public string GetMACAddress() { //得到 MAC的注册表键 RegistryKey macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control") .OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}"); IList<string> list = macRegistry.GetSubKeyNames().ToList(); IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); var adapter = nics.First(o => o.Name == "本地连接"); if (adapter == null) return null; return string.Empty; } /// <summary> /// 设置MAC地址 /// </summary> /// <param name="newMac"></param> public void SetMACAddress(string newMac) { string macAddress; string index = GetAdapterIndex(out macAddress); if (index == null) return; //得到 MAC的注册表键 RegistryKey macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control") .OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}").OpenSubKey(index, true); if (string.IsNullOrEmpty(newMac)) { macRegistry.DeleteValue("NetworkAddress"); } else { macRegistry.SetValue("NetworkAddress", newMac); macRegistry.OpenSubKey("Ndi", true).OpenSubKey("params", true).OpenSubKey("NetworkAddress", true).SetValue("Default", newMac); macRegistry.OpenSubKey("Ndi", true).OpenSubKey("