新思想

C# 网卡配置 源代码

C# 网卡配置 源代码

NICConfig

// This program can run in Windows 7.
// This program can't run in Windows Server 2012 R2, I don't know why ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
using System.Net;
using Microsoft.Win32;

namespace NICConfig
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private static string Dopadding(int i)
        {
            string str = "";
            switch (i.ToString().Length)
            {
                case 1:
                    str = "000" + i.ToString();
                    break;
                case 2:
                    str = "00" + i.ToString();
                    break;
                case 3:
                    str = "0" + i.ToString();
                    break;
                case 4:
                    str = i.ToString();
                    break;
            }
            return str;
        }

        public void LoadInfo(String NICDescription)
        {
            ipAddresstextBox.Clear();
            ipSubnettextBox.Clear();
            defaultIPGatewaytextBox.Clear();
            macAddresstextBox.Clear();
            DNS1textBox.Clear();
            DNS2textBox.Clear();

            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
            ManagementObjectCollection queryCollection = query.Get();

            foreach (ManagementObject items in queryCollection)
            {
                if (items["Description"].ToString().Trim() == NICDescription.Trim())
                {
                    //descriptioncomboBox.Items.Add(items["Description"]);
                    //descriptioncomboBox.SelectedIndex = 0;
                    ipAddresstextBox.Text = ((string[])items["IPAddress"])[0];
                    ipSubnettextBox.Text = ((string[])items["IPSubnet"])[0];
                    defaultIPGatewaytextBox.Text = ((string[])items["DefaultIPGateway"])[0];
                    macAddresstextBox.Text = ((string)items["MACAddress"]).Replace(":", "");
                    DNS1textBox.Text = ((string[])items["DNSServerSearchOrder"])[0];
                    DNS2textBox.Text = ((string[])items["DNSServerSearchOrder"])[1];
                    break;
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
            ManagementObjectCollection queryCollection = query.Get();

            foreach (ManagementObject items in queryCollection)
            {
                descriptioncomboBox.Items.Add(items["Description"]);
            }
            descriptioncomboBox.SelectedIndex = 0;
            LoadInfo(descriptioncomboBox.Text);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            bool IsSussce = true;
            try
            {
                ManagementBaseObject inPar = null;
                ManagementBaseObject outPar = null;
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();

                foreach (ManagementObject mo in moc)
                {
                    if (!(bool)mo["IPEnabled"] || (mo["Description"].ToString().Trim() != descriptioncomboBox.Text.Trim()))
                        continue;

                    if ((!string.IsNullOrWhiteSpace(ipAddresstextBox.Text)) && ipAddresstextBox.Modified)
                    {
                        inPar = mo.GetMethodParameters("EnableStatic");
                        inPar["IPAddress"] = new string[] { ipAddresstextBox.Text.ToString().Trim() };
                        inPar["SubnetMask"] = new string[] { ipSubnettextBox.Text.ToString().Trim() };
                        outPar = mo.InvokeMethod("EnableStatic", inPar, null);
                        if (int.Parse(outPar["returnValue"].ToString()) != 0)
                            throw new Exception("很遗憾,发生未知错误,错误代号:'" + outPar["returnValue"].ToString() + "'请检查你的输入参数");
                    }

                    if ((!string.IsNullOrWhiteSpace(defaultIPGatewaytextBox.Text)) && defaultIPGatewaytextBox.Modified)
                    {
                        inPar = mo.GetMethodParameters("SetGateways");
                        inPar["DefaultIPGateway"] = new string[] { defaultIPGatewaytextBox.Text.ToString().Trim() };
                        outPar = mo.InvokeMethod("SetGateways", inPar, null);
                        if (int.Parse(outPar["returnValue"].ToString()) != 0)
                            throw new Exception("很遗憾,发生未知错误,错误代号:'" + outPar["returnValue"].ToString() + "'请检查你的输入参数");
                    }

                    if ((!string.IsNullOrWhiteSpace(DNS1textBox.Text)) && (DNS1textBox.Modified || DNS2textBox.Modified))
                    {
                        inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                        inPar["DNSServerSearchOrder"] = new string[] { DNS1textBox.Text.ToString().Trim(), DNS2textBox.Text.ToString().Trim() };
                        outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                        if (int.Parse(outPar["returnValue"].ToString()) != 0)
                            throw new Exception("很遗憾,发生未知错误,错误代号:'" + outPar["returnValue"].ToString() + "'请检查你的输入参数");
                    }

                    if ((!string.IsNullOrWhiteSpace(macAddresstextBox.Text.Trim())) && macAddresstextBox.Modified)
                    {
                        RegistryKey hklm = Registry.LocalMachine;
                        string last = "";
                        string sign = "";

                        string subKeyPath = @"SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\";
                        //string subKeyPath = @"SYSTEM\ControlSet002\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\";

                        for (int i = 0; i <= 100; i++)
                        {
                            last = Dopadding(i);
                            RegistryKey sys = hklm.OpenSubKey(subKeyPath + last, true);
                            sign = sys.GetValue("DriverDesc").ToString();

                            if (descriptioncomboBox.Text.IndexOf(sign) > -1)
                            {
                                sys.SetValue("NetWorkAddress", macAddresstextBox.Text.Replace(":", "").Replace("-", ""));

                                // From http://code.msdn.microsoft.com/windowsdesktop/Disableenable-network-8112f642
                                // But it can't disable/enable network in Windows
                                // mo.InvokeMethod("Disable", null);
                                // System.Threading.Thread.Sleep(2000);
                                // mo.InvokeMethod("Enable", null);
                                // 原因:
                                // Win32_NetworkAdapter class 支持IPv4,Win32_NetworkAdapterConfiguration 既支持IPv4 又支持 IPv6。见 http://msdn.microsoft.com/en-us/library/aa822883
                                // Win32_NetworkAdapter class 支持禁用和启用网络。见 http://msdn.microsoft.com/en-us/library/aa394216
                                // Win32_NetworkAdapterConfiguration 不支持禁用和启用网络。见 http://msdn.microsoft.com/en-us/library/aa394217

                                ManagementObject crtNetworkAdapter = new ManagementObject();
                                string strWQuery = string.Format("SELECT Description, DeviceID, ProductName, NetEnabled, NetConnectionStatus FROM Win32_NetworkAdapter");
                                ObjectQuery oQuery = new ObjectQuery(strWQuery);
                                ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oQuery);
                                ManagementObjectCollection networkAdapters = oSearcher.Get();

                                foreach (ManagementObject networkAdapter in networkAdapters)
                                {
                                    if (networkAdapter["Description"].ToString().Trim() == descriptioncomboBox.Text.Trim())
                                    {
                                        //for Windows 8 ???
                                        //inPar = networkAdapter.GetMethodParameters("ChangeStartMode");
                                        //inPar["startmode"] = "Manual";
                                        //networkAdapter.InvokeMethod("ChangeStartMode", inPar, null);

                                        networkAdapter.InvokeMethod("Disable", null);
                                        System.Threading.Thread.Sleep(1000);
                                        networkAdapter.InvokeMethod("Enable", null);
                                        break;
                                    }
                                }
                                sys.Flush();
                                sys.Close();
                                break;
                            }
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                IsSussce = false;
            }
            finally
            {
                if (IsSussce)
                {
                    MessageBox.Show("恭喜,修改完成!", "提示", MessageBoxButtons.OK);
                }
                else
                {
                    MessageBox.Show("很遗憾,修改失败!", "提示", MessageBoxButtons.OK);
                }
                LoadInfo(descriptioncomboBox.Text);
            }
        }

        private void descriptioncomboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadInfo(descriptioncomboBox.Text);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bool IsSussce = true;
            try
            {
                ManagementBaseObject inPar = null;
                //ManagementBaseObject outPar = null;
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();

                foreach (ManagementObject mo in moc)
                {
                    if (!(bool)mo["IPEnabled"] || (mo["Description"].ToString().Trim() != descriptioncomboBox.Text.Trim()))
                        continue;

                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces" + mo.GetPropertyValue("SettingID").ToString(), true);

                    //设置注册表的内容
                    if (rk != null)
                    {
                        rk.SetValue("IPAddress", "0.0.0.0");
                        rk.DeleteValue("SubnetMask");
                        rk.DeleteValue("DefaultGateway");
                        rk.DeleteValue("DisableDhcpOnConnect");
                        rk.DeleteValue("NameServer");
                        rk.SetValue("EnableDHCP", "1", RegistryValueKind.DWord);
                        //rk.SetValue("IPAddress", "0.0.0.0");
                        //rk.SetValue("SubnetMask", "");
                        //rk.SetValue("DefaultGateway", "");
                        //rk.SetValue("NameServer", "");
                        //rk.SetValue("EnableDHCP", "dword:00000001");    //自动
                        //Convert.ToInt16(1);
                        rk.Flush();
                        rk.Close();
                    }
                    //设置 IP 自动获取
                    mo.InvokeMethod("EnableDHCP", null, null);
                    //设置 DNS 自动获取
                    inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                    inPar["DNSServerSearchOrder"] = null;
                    mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);

                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                IsSussce = false;
            }
            finally
            {
                if (IsSussce)
                {
                    MessageBox.Show("恭喜,修改完成!", "提示", MessageBoxButtons.OK);
                }
                else
                {
                    MessageBox.Show("很遗憾,修改失败!", "提示", MessageBoxButtons.OK);
                }
                LoadInfo(descriptioncomboBox.Text);
            }
        }

    }
}

源程序下载

执行程序下载

posted on 2015-12-01 00:07  新思想  阅读(1137)  评论(0)    收藏  举报

导航