C#遠程關機 C#遠程關機代碼
發(fā)表時間:2023-07-24 來源:明輝站整理相關軟件相關文章人氣:
[摘要]C#遠程關機 C#遠程關機代碼 WMI中Win32_OperationSystem的方法Win32ShutDown(flag)中flag的參數(shù)可以是下表中的任意一種: 值 描述 0 注銷 0 + 4...
C#遠程關機 C#遠程關機代碼
WMI中Win32_OperationSystem的方法Win32ShutDown(flag)中flag的參數(shù)可以是下表中的任意一種:
值 描述
0 注銷
0 + 4 強制注銷
1 關機
1 + 4 強制關機
2 重起
2 + 4 強制重起
8 關閉電源
8 + 4 強制關閉電源
下面是示例:
//關閉計算機
private void btn_Shutdown_Click(object sender, EventArgs e)
{
string IPShutdown = "192.168.1.100";
DialogResult dlResult = MessageBox.Show("確實要關閉“" + IPShutdown + "”電源嗎?", "請確認", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dlResult == DialogResult.Yes)
{
string[] inParams ={ "8", "4" };
BootComputer ShutdownBootComputer = new BootComputer();
ShutdownBootComputer.strIp = IPShutdown;
ShutdownBootComputer.strAdmin = txtAdmin.Text.Trim();
ShutdownBootComputer.strPassword = txtPassword.Text.Trim();
ShutdownBootComputer.strMothod = "Win32Shutdown";
ShutdownBootComputer.inParams = inParams;
ShutdownBootComputer.BootMachine();
}
}
//關閉重啟計算機(支持多線程)
public class BootComputer
{
public string strIp, strAdmin, strPassword, strMothod;
public string[] inParams;
public void BootMachine()
{
ConnectionOptions BootConn = new ConnectionOptions();
BootConn.Username = strAdmin;
BootConn.Password = strPassword;
ManagementScope ms = new ManagementScope("\\\\" + strIp + "\\root\\cimv2", BootConn);
ms.Options.EnablePrivileges = true;
if (!string.IsNullOrEmpty(strAdmin) && !string.IsNullOrEmpty(strPassword))
{
try { ms.Connect(); }
catch { }
}
if (ms.IsConnected)
{
try
{
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms, oq);
ManagementObjectCollection moc = mos.Get();
foreach (ManagementObject mo in moc)
{
string[] ss = inParams;
mo.InvokeMethod(strMothod, ss);
}
}
catch (Exception ex)
{
MessageBox.Show(strIp + ":" + ex.Message + "網(wǎng)絡不通或用戶名、密碼不正確!");
}
}
}
}
學習教程快速掌握從入門到精通的電腦知識