using System;
using System.Management;
namespace ArLi.CommonPrj {
public class PLMM007_WMI {
public static readonly System.Version myVersion = new System.Version(1,1);
private ManagementBaseObject iObj = null;
private ManagementBaseObject oObj = null;
private ManagementClass mc = new ManagementClass("Win32_Service");
private readonly ManagementObjectCollection moc;
public PLMM007_WMI(){
moc = mc.GetInstances();
}
///
/// 查询服务模式
///
/// 要查询的服务,为null 表示返回所有已禁用服务
public string GetDisabled(string serviceName) {
string s="";
foreach(ManagementObject mo in moc) {
if (serviceName != null) { //服务如果不为null
if (((string)mo["Name"]).ToUpper() == serviceName.ToUpper()) {
return (string)mo["StartMode"];
}
}
if ((string) mo["StartMode"] == "Disabled") {
s += mo["Name"].ToString() + "/r/n"; //自己改成想要的格式
//你可以用displayname,上面的是ServiceName,下面这个是DisplayName
//s += mo["DisplayName"].ToString() + "/r/n";
};
}
return s;
}
///
/// 设置模式
///
/// 服务名
/// 模式,比如:Boot/System/Automatic/Manual/Disabled
/// 操作完成 1,否则 0
public int ChangeTo(string serviceName, string startMode) {
foreach(ManagementObject mo in moc) {
//服务名存在
if (((string)mo["Name"]).ToUpper() == serviceName.ToUpper()) {
// 如果服务已经是指定模式则返回
if ((string) mo["StartMode"] == startMode) return 0;
// 设置服务模式
iObj = mo.GetMethodParameters("ChangeStartMode");
iObj["StartMode"] = startMode;
oObj = mo.InvokeMethod("ChangeStartMode", iObj, null);
return 1;
}
}
return 0;
}
}
}
ArLi.CommonPrj.PLMM007_WMI o = new ArLi.CommonPrj.PLMM007_WMI();
//比如剪贴板设置为自动启动
o.ChangeTo("ClipSrv","Automatic");