[C#]程式更改電腦IP位置與電腦名稱

  • 21308
  • 0
  • 2012-01-31

摘要:[C#]程式更改電腦IP位置與電腦名稱

更改多個網卡與電腦名稱

程式畫面:

詳細程式碼如下:

using System;
using System.Management; // System.Management 命名空間 需加入參考System.Management
using System.Runtime.InteropServices;
using System.Text.RegularExpressions; // System.Collections 命名空間
using System.Windows.Forms;

namespace SetIPAndHostName
{
    public partial class Form1 : Form
    {
        ManagementObject objCls; // ManagementObject 類別 , 表示 WMI 執行個體。
        string strCls = "Win32_NetworkAdapterConfiguration"; // WMI 名稱空間 ( Namespace )
        string strNS = "root\\CIMV2"; // WMI 類別 (Class)
        string strIndex; // 用來記錄網路介面卡 Index

        [DllImport("kernel32.dll")]
        static extern bool SetComputerName(string lpComputerName);
        [DllImport("kernel32.dll")]
        static extern bool SetComputerNameEx(_COMPUTER_NAME_FORMAT iType, string lpComputerName);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            GetAdtInfo(); // 呼叫 GetAdtInfo 程序來取得網路介面卡資訊
            txt_Old_PCName.Text = System.Windows.Forms.SystemInformation.ComputerName;
        }

        private void GetAdtInfo()
        {
            // 指定查詢網路介面卡組態 ( IPEnabled 為 True 的 )
            string strQry = "Select * from Win32_NetworkAdapterConfiguration where IPEnabled=True";

            // ManagementObjectSearcher 類別 , 根據指定的查詢擷取管理物件的集合。
            ManagementObjectSearcher objSc = new ManagementObjectSearcher(strQry);

            // 使用 Foreach 陳述式 存取集合類別中物件 (元素)
            // Get 方法 , 叫用指定的 WMI 查詢 , 並傳回產生的集合。
            foreach (ManagementObject objQry in objSc.Get())
            {
                // 取網路介面卡資訊
                ComboBox.Items.Add(objQry["Caption"]); // 將 Caption 新增至 ComboBox

            }
            ComboBox.SelectedIndex = 0;//預設選擇第一個
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (IsIPAddress(txtIP.Text))
            {
                string strIP = txtIP.Text;  // IP 位址
                string strSubmask = txtSubmask.Text; // 子網路遮罩
                string strGateway = txtGateway.Text; // 預設閘道
                string strDNS1 = txtDNS1.Text; // 慣用 DNS 伺服器
                string strDNS2 = txtDNS2.Text; // 其他 DNS 伺服器
                strIndex = label7.Text; //取的要設定之網卡Index
                // 呼叫 SetNetCfg 程序 , 設定網路介面卡組態
                SetNetCfg(strIP, strSubmask, strGateway, strDNS1, strDNS2);
            }
            else
            {
                MessageBox.Show("IP位置錯誤,請檢查!", "IP錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void SetNetCfg(string strIP, string strSubmask, string strGateway, string strDNS1, string strDNS2)
        {
            // 建立 ManagementObject 物件 ( Scope , Path , options )
            objCls = new ManagementObject(strNS, strCls + ".INDEX=" + strIndex, null);

            ManagementBaseObject objInPara; // 宣告管理物件類別的基本類別

            objInPara = objCls.GetMethodParameters("EnableStatic");
            objInPara["IPAddress"] = new string[] { strIP }; // 設定 "IP" 屬性
            objInPara["SubnetMask"] = new string[] { strSubmask }; // 設定 "子網路遮罩" 屬性
            objCls.InvokeMethod("EnableStatic", objInPara, null);

            objInPara = objCls.GetMethodParameters("SetGateways");
            objInPara["DefaultIPGateway"] = new string[] { strGateway }; // 設定 "Gateway" 屬性
            objCls.InvokeMethod("SetGateways", objInPara, null);

            objInPara = objCls.GetMethodParameters("SetDNSServerSearchOrder");
            objInPara["DNSServerSearchOrder"] = new string[] { strDNS1, strDNS2 }; // 設定 "DNS" 屬性
            objCls.InvokeMethod("SetDNSServerSearchOrder", objInPara, null);

            // GetMethodParameters 方法 : 用來取得 SetDNSServerSearchOrder 參數清單。
            // InvokeMethod 方法 : 在物件上叫用方法。
            MessageBox.Show("IP設定完成!", "設定完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetNetInfo(ComboBox.SelectedItem.ToString());
        }

        void GetNetInfo(string strNetAdapterName)
        {
            // 指定查詢網路介面卡組態 ( IPEnabled 為 True 的 )
            string strQry = "Select * from Win32_NetworkAdapterConfiguration where IPEnabled=True";

            // ManagementObjectSearcher 類別 , 根據指定的查詢擷取管理物件的集合。
            ManagementObjectSearcher objSc = new ManagementObjectSearcher(strQry);

            // 使用 Foreach 陳述式 存取集合類別中物件 (元素)
            // Get 方法 , 叫用指定的 WMI 查詢 , 並傳回產生的集合。
            foreach (ManagementObject objQry in objSc.Get())
            {
                //判斷是否與選取網卡名稱一樣
                if (objQry["Caption"].ToString() == strNetAdapterName)
                {
                    label3.Text = objQry["MACAddress"].ToString();
                    label5.Text = objQry["ServiceName"].ToString();
                    label7.Text = objQry["Index"].ToString();
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            strIndex = label7.Text; //取的要設定之網卡Index
            SetAuto(); // 呼叫 SetAuto 程序 , 設定網路介面卡組態
        }

        private void SetAuto()
        {
            // 建立 ManagementObject 物件 ( Scope , Path , options )
            objCls = new ManagementObject(strNS, strCls + ".INDEX=" + strIndex, null);
            // InvokeMethod 方法 : 在物件上叫用方法。
            objCls.InvokeMethod("EnableDHCP", null); // 設定自動取得 IP
            objCls.InvokeMethod("ReleaseDHCPLease", null); // 釋放 IP
            objCls.InvokeMethod("RenewDHCPLease", null); // 重新取得 IP
            objCls.InvokeMethod("SetDNSServerSearchOrder", null);//設定自動取得DNS
            MessageBox.Show("自動取得IP設定完成!", "設定完成", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        public static bool IsIPAddress(string ip)//驗證IP位置是否為正確
        {
            string[] arr = ip.Split('.');
            if (arr.Length != 4)
                return false;
            string pattern = @"\d{1,3}";
            for (int i = 0; i < arr.Length; i++)
            {
                string d = arr[i];
                if (i == 0 && d == "0")
                    return false;
                if (!Regex.IsMatch(d, pattern))
                    return false;
                if (d != "0")
                {
                    d = d.TrimStart('0');
                    if (d == "")
                        return false;
                    if (int.Parse(d) > 255)
                        return false;
                }
            } return true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                ManagementClass mmc = new ManagementClass("Win32_OperatingSystem");
                mmc.Scope.Options.EnablePrivileges = true; //取得作業系統使用者權限
                foreach (ManagementObject mo in mmc.GetInstances())
                {
                    mo.InvokeMethod("Reboot", null, null); //呼叫一般重新啟動
                }
                mmc.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string MachineName = txt_New_PCName.Text.Trim();
            if (MachineName.Length == 0)
            {
                MessageBox.Show("請填寫電腦名稱!", "錯誤!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            bool succeeded = SetComputerName(MachineName);
            bool succeeded2 = SetComputerNameEx(_COMPUTER_NAME_FORMAT.ComputerNamePhysicalDnsHostname, MachineName);

            if (succeeded && succeeded2)
            {
                MessageBox.Show("更改完成!請重新開機!", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                button3.Enabled = true;
                DialogResult dr = MessageBox.Show("是否立即重新啟動電腦?", "重新啟動", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (dr==DialogResult.Yes)
                {
                    button3.PerformClick();//呼叫button3事件
                }
                else
                {
                    return;
                }
            }
            else
            {
                MessageBox.Show("電腦名稱錯誤!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        enum _COMPUTER_NAME_FORMAT
        {
            ComputerNameNetBIOS,
            ComputerNameDnsHostname,
            ComputerNameDnsDomain,
            ComputerNameDnsFullyQualified,
            ComputerNamePhysicalNetBIOS,
            ComputerNamePhysicalDnsHostname,
            ComputerNamePhysicalDnsDomain,
            ComputerNamePhysicalDnsFullyQualified,
            ComputerNameMax
        };
    }
}

程式碼下載:SetIPAndHostName.rar

我只是個小小的入門者