【自编】修改网卡部分属性

最近写的一个修改网卡IP,DNS,MASK,GATEWAY,MAC的小程序,代码很烂,出了能RUN之外一无是处,姑且贴出来站个位置吧
除MAC之外都是用WMI实现的,改MAC是修改注册表中键值
windows pro sp2 / .net framework 2.0 / vs 2005

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Management;
using Microsoft.Win32;

namespace 网络测试
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            BindNetcard();
        }
        private void BindNetcard()
        {
            //得到本机拥有的网卡信息
           
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();

            string Netcard;
            foreach (ManagementObject eachMo in moc)
            {
                if (!(bool)eachMo["IPEnabled"])
                    continue;
                Netcard = eachMo["Description"].ToString();
                if (Netcard != null)
                {                   
                    this.comboBox1.Items.Add(Netcard);
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string Netcard = comboBox1.SelectedItem.ToString();
            if (Netcard != null)
            {
                //根据选择的网卡名搜索

                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();

                foreach (ManagementObject eachMo in moc)
                {
                    if (!(bool)eachMo["IPEnabled"])
                        continue;
                    if (Netcard == eachMo["Description"].ToString())
                    {
                        string[] tip;
                        try
                        {
                            //获得IP,网关,子网掩码,DNS
                            tip = (string[])eachMo["IPAddress"];
                            this.txtIP.Text = tip[0];
                            tip = (string[])eachMo["IPSubnet"];
                            this.txtSN.Text = tip[0];
                            tip = (string[])eachMo["DefaultIPGateway"];
                            this.txtGw.Text = tip[0];
                            tip = (string[])eachMo["DNSServerSearchOrder"];
                            this.txtDNS.Text = tip[0];

                            //获得MAC地址
                            this.txtMAC.Text = (string)eachMo["MACAddress"];

                            //这里我又偷懒搞了一个隐藏的LABEL用于同步注册表和WMI的对应值
                            this.labMac.Text = (string)eachMo["MACAddress"];

                            this.button1.Enabled = true;

                            return;
                        }
                        catch (Exception ee)
                        {
                            //这里可能出现由于某些网卡属性没有设置而导致的异常,本人因为偷懒而没有去写
                            MessageBox.Show("出现错误,错误代码为" + ee.Message);
                            return;
                        }
                        finally
                        {
                            ;
                        }
                    }
                }
            }
            else
            {
                return;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (CheckIP()==false)
                return;
            if (this.radioButton1.Checked == false && this.radioButton2.Checked == false)
                MessageBox.Show("请选择是自动分配IP还是静态IP");


            //状态显示为正在修改
            this.libSta.Text = "正在修改中,请稍后。";
            this.progressBar1.Maximum = 100;
            this.progressBar1.Minimum = 0;

            //修改除MAC外的网卡属性
            string Netcard = comboBox1.SelectedItem.ToString();
            if (Netcard != null)
            {
                //找到待修改网卡
                ManagementBaseObject inPar = null;
                ManagementBaseObject outPar = null;

                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();

                foreach (ManagementObject eachMo in moc)
                {
                    if (!(bool)eachMo["IPEnabled"])
                    {
                        continue;
                    }
                    try
                    {
                        if (Netcard == eachMo["Description"].ToString())
                        {
                            this.progressBar1.Value = 50;
                            //使用DHCP
                            if (this.radioButton1.Checked == true)
                            {
                                inPar = eachMo.GetMethodParameters("EnableDHCP");
                                outPar = eachMo.InvokeMethod("EnableDHCP", inPar, null);
                                this.progressBar1.Value = 100;
                                this.libSta.Text = "修改完成";                               
                                MessageBox.Show("成功将IP设置修改为DHCP(自动分配IP)");
                                this.libSta.Text = "";
                            }
                            //使用static ip
                            else if (this.radioButton2.Checked == true)
                            {
                                //修改IP和子网掩码
                                inPar = eachMo.GetMethodParameters("EnableStatic");
                                inPar["IPAddress"] = new string[] { this.txtIP.Text };
                                inPar["SubnetMask"] = new string[] { this.txtSN.Text };
                               
                                outPar = eachMo.InvokeMethod("EnableStatic", inPar, null);

                                this.progressBar1.Value = 70;

                                //修改网关

                                inPar = eachMo.GetMethodParameters("SetGateways");
                                inPar["DefaultIPGateway"] = new string[] { this.txtGw.Text };
                                outPar = eachMo.InvokeMethod("SetGateways", inPar,null);

                                this.progressBar1.Value = 85;

                                //修改DNS

                                inPar = eachMo.GetMethodParameters("SetDNSServerSearchOrder");
                                inPar["DNSServerSearchOrder"] = new string[] { this.txtDNS.Text };
                                outPar = eachMo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);

                                this.progressBar1.Value = 100;
                                this.libSta.Text = "修改完成";

                                MessageBox.Show("成功将IP设置修改为使用静态IP");

                                this.libSta.Text = "";
                            }
                        }
                    }
                    catch (Exception ee)
                    {
                        MessageBox.Show("出现错误,错误代码为" + ee.Message);
                    }
                    finally
                    {
                        ;
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult DR = MessageBox.Show("确定要修改网卡MAC地址(注册表值)么?\n搞坏了不负责。\n如果要改,建议先记录一下原地址。", "你要来真的么", MessageBoxButtons.OKCancel);
            if (DR == DialogResult.Cancel)
                return;
            //修改MAC地址
            //先查找到该网卡在注册表中的位置
            string LOCAL = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}\\000";
            string NetLocal = "";
            RegistryKey okey = Registry.LocalMachine;
            for (int i = 0; i < 10; ++i)
            {
                NetLocal = LOCAL;
                NetLocal += i.ToString();
                okey = Registry.LocalMachine.OpenSubKey(NetLocal,true);
                try
                {
                    if (okey != null)
                    {
                        if (okey.GetValue("NetworkAddress") != null && okey.GetValue("NetworkAddress").ToString() == this.labMac.Text.Replace(":", ""))
                        {
                            okey.SetValue("NetworkAddress", this.txtMAC.Text.Replace(":", ""));
                            DialogResult MyDr = MessageBox.Show("修改注册表成功,重启之后方可实效。", "MAC修改成功", MessageBoxButtons.OKCancel);
                        }
                    }
                }
                catch(Exception ee)
                {
                    MessageBox.Show("出现错误,错误代码为" + ee.Message);
                }
                finally
                {
                    ;
                }
            }
        }


        //顾名思义,重启计算机
        private void RebootComputer()
        {
            string[] ss = { "" };
            try
            {
                ManagementClass mc = new ManagementClass("Win32_OperatingSystem");
                mc.InvokeMethod("reboot", ss);
            }
            catch (Exception ee)
            {
                MessageBox.Show("出现错误,错误代码为" + ee.Message);
            }
        }

        //检查IP是否合格
        private bool CheckIP()
        {
            IPAddress tt;
            try
            {
                tt = IPAddress.Parse(this.txtIP.Text);
            }
            catch(Exception ee)
            {
                if (ee.Message == "指定了无效的 IP 地址。")
                    MessageBox.Show("IP格式错误");
                return false;
            }
            try
            {
                tt = IPAddress.Parse(this.txtSN.Text);
            }
            catch (Exception ee)
            {
                if (ee.Message == "指定了无效的 IP 地址。")
                    MessageBox.Show("子网掩码格式错误");
                return false;
            }
            try
            {
                tt = IPAddress.Parse(this.txtGw.Text);
            }
            catch (Exception ee)
            {
                if (ee.Message == "指定了无效的 IP 地址。")
                    MessageBox.Show("网关格式错误");
                return false;
            }
            try
            {
                tt = IPAddress.Parse(this.txtDNS.Text);
            }
            catch (Exception ee)
            {
                if (ee.Message == "指定了无效的 IP 地址。")
                    MessageBox.Show("DNS格式错误");
                return false;
            }
            return true;           
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            this.txtDNS.Enabled = false;
            this.txtGw.Enabled = false;
            this.txtIP.Enabled = false;
            this.txtSN.Enabled = false;
            if (this.button2.Enabled == false)
                this.button2.Enabled = true;
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            this.txtDNS.Enabled = true;
            this.txtGw.Enabled = true;
            this.txtIP.Enabled = true;
            this.txtSN.Enabled = true;
            if (this.button2.Enabled == false)
                this.button2.Enabled = true;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        //刷新各项
        private void button3_Click(object sender, EventArgs e)
        {
            if (this.comboBox1.SelectedItem == null)
            {
                return;
            }
            comboBox1_SelectedIndexChanged(sender, e);
        }

        //弹出软件介绍
        private void 关于此软件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            about newa = new about(this);
            newa.ShowDialog();
        }
    }
}

posted on 2006-11-13 16:07  AnewR  阅读(1227)  评论(0)    收藏  举报