上周,Boss和我说,他儿子夜里爬起来用笔记本在被窝里玩CF,问路由器可以解决么,我看了是TPLINK的普通家用无线路由器,不支持禁用CF客户端网游,可以通过配置端口屏蔽什么的,但是白天又要开启,想想麻烦。还是写个win服务,定时禁用网卡和定时启用网卡。
思路是分为两步,
1. 要先获取到无线网卡的ID。
2. 然后定时关闭/启用这个无线网卡。
程序呢,也是分为2部分,
1. 用了winform 去获取所有网络适配器信息,看看找到无线网卡,然后记下网卡名。
2. 用win服务去遍历Win32_NetworkAdapter 的信息,符合网卡的,就InvokeMethod, Disable/Enable 。
很简单,winform程序就遍历了下Win32_NetworkAdapter,然后2个按钮来测试是否可以正常关闭 和 开启无线网卡。
有点需要注意,需要引用System.Management.dll ,using System.Management;
1 /// <summary> 2 /// 网卡列表 3 /// </summary> 4 public void NetWorkList() 5 { 6 string manage = "SELECT * From Win32_NetworkAdapter"; 7 ManagementObjectSearcher searcher = new ManagementObjectSearcher(manage); 8 ManagementObjectCollection collection = searcher.Get(); 9 List<string> netWorkList = new List<string>(); 10 foreach (ManagementObject obj in collection) 11 { 12 netWorkList.Add(obj["Name"].ToString()); 13 label5.Text += obj["Name"].ToString() + "\r\n"; 14 } 15 this.cmbNetWork.DataSource = netWorkList; 16 } 17 18 /// <summary> 19 /// 网卡状态 20 /// </summary> 21 /// <param name="netWorkName">网卡名</param> 22 /// <returns></returns> 23 public bool NetWorkState(string netWorkName) 24 { 25 string netState = "SELECT * From Win32_NetworkAdapter"; 26 ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState); 27 ManagementObjectCollection collection = searcher.Get(); 28 foreach (ManagementObject manage in collection) 29 { 30 if (manage["Name"].ToString() == netWorkName) 31 { 32 return true; 33 } 34 } 35 return false; 36 } 37 38 /// <summary> 39 /// 得到指定网卡 40 /// </summary> 41 /// <param name="networkname">网卡名字</param> 42 /// <returns></returns> 43 public ManagementObject NetWork(string networkname) 44 { 45 string netState = "SELECT * From Win32_NetworkAdapter"; 46 ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState); 47 ManagementObjectCollection collection = searcher.Get(); 48 foreach (ManagementObject manage in collection) 49 { 50 if (manage["Name"].ToString() == networkname) 51 { 52 return manage; 53 } 54 } 55 return null; 56 }
1 /// <summary> 2 /// 禁用网卡 3 /// </summary>5 4 /// <param name="netWorkName">网卡名</param> 5 /// <returns></returns> 6 private static bool DisableNetWork(ManagementObject network) 7 { 8 try 9 { 10 network.InvokeMethod("Disable", null); 11 return true; 12 } 13 catch 14 { 15 return false; 16 } 17 } 18 /// <summary> 19 /// 启用网卡 20 /// </summary> 21 /// <param name="netWorkName">网卡名</param> 22 /// <returns></returns> 23 private static bool EnableNetWork(ManagementObject network) 24 { 25 try 26 { 27 network.InvokeMethod("Enable", null); 28 return true; 29 } 30 catch 31 { 32 return false; 33 } 34 }
再来就是 windows服务,代码其实就是和winform程序一样,没啥区别,只是定时注意下,另appconfig 配置节点:
网卡名称,禁止时间、启用时间。
代码下载 (控件、方法、判断空等规则可以无视,这里只是作为测试用的)
【版权声明】转载请注明出处: http://www.cnblogs.com/yiayi/p/3526735.html