public class ManageComp
{
ManagementObject _moOpSystem;
public ManageComp()
{
ManagementScope scope = new ManagementScope(
"\\\\.\\root\\cimv2",
new ConnectionOptions() { EnablePrivileges = true });
scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);
foreach(ManagementObject m in searcher.Get())
{
_moOpSystem = m;
}
}
public void RebootComputer()
{
_moOpSystem.InvokeMethod("Reboot", null);
}
}
static class Program
{
public static ManageComp ManComp = new ManageComp();
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
new Thread(new ThreadStart(delegate()
{
Application.Run(new FormMain()
{
Text = "Another Thread"
});
})).Start();
Application.Run(new FormMain()
{
Text = "Main Thread"
});
}
}
当我从标题为“主线程”的表单中调用 RebootComputer 时,计算机成功重新启动,但从标题为“另一个线程”的表单中调用相同的方法会导致异常,提示“未保留特权”
这是按钮点击代码
private void button1_Click(object sender, EventArgs e)
{
Program.ManComp.RebootComputer();
}
我怎样才能克服这个奇怪的问题?为什么会这样?