2011年12月20日 星期二

[C#] 取得電腦名稱、變更電腦名稱、重新開機

因為要管理的電腦太多,雖然已經使用 IP、Terminal 來管理
但是還是常常找不到 電腦再哪裡?  所以準備使用 電腦名稱來管理。

完整原始碼下載















//取得電腦名稱
System.Windows.Forms.SystemInformation.ComputerName

//變更電腦名稱
 [DllImport("kernel32.dll")]
 static extern bool SetComputerName(string lpComputerName);
 [DllImport("kernel32.dll")]
 static extern bool SetComputerNameEx(_COMPUTER_NAME_FORMAT iType, string lpComputerName);


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


        private void button1_Click(object sender, EventArgs e)
        {
            string MachineName = txt_New_PCName.Text.Trim();
            if (MachineName.Length == 0)
            {
                button1.Text = "NG";
                 return;
            }

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

            if (succeeded && succeeded2)
            {
                button1.Text = "OK,請重開機!";
                btn_Restrate.Visible = true;
            }
            else
            {
                button1.Text="NG";
            }
        }



//重新開機
         private void btn_Restrate_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 Q)
            {
                MessageBox.Show(Q.Message);
            }
        }

沒有留言:

張貼留言