首先需要添加引用using namespace System::Management;并且在vs中引用System.Managemen.dll
测试发现270个服务获取还是有点慢,不知道是否还有优化的余地。
//一个服务的基本信息
ref class OneServerInfo
{
public:
String ^Name; //服务名称
String ^DisplayName; //显示名称
String ^StartMode; //启动方式
String ^Started; //状态
String ^PathName; //路径
};
//获取所有服务的信息
array<OneServerInfo ^> ^ GetAllServerInfo(void)
{
array<OneServerInfo^> ^ServerArray = nullptr; //存放所有的服务信息
int i;
try
{
//获得服务集合
ManagementObjectSearcher ^searcher = gcnew ManagementObjectSearcher("SELECT * FROM Win32_Service");
if (searcher != nullptr)
{
System::Management::ManagementObjectCollection^ mo = searcher->Get();
if (mo != nullptr)
{
OneServerInfo ^info;
System::Management::ManagementObjectCollection::ManagementObjectEnumerator^ mEnumerator = mo->GetEnumerator();
if (mEnumerator != nullptr)
{
ServerArray = gcnew array<OneServerInfo^>(mo->Count);
for (i = 0; i < mo->Count;i ++)
{
info = gcnew OneServerInfo;
if (mEnumerator->MoveNext() == false) break;
System::Management::ManagementBaseObject^ mObj = mEnumerator->Current;
if (mObj == nullptr) break;
info->Name = mObj->GetPropertyValue("Name")->ToString(); //服务名称
info->DisplayName = mObj->GetPropertyValue("DisplayName")->ToString(); //显示名称
info->StartMode = mObj->GetPropertyValue("StartMode")->ToString(); //启动方式
info->Started = mObj->GetPropertyValue("Started")->ToString(); //状态
info->PathName = mObj->GetPropertyValue("PathName")->ToString(); //路径
//mObj->GetPropertyValue("StartName")->ToString(); //账户登录方式-这个暂时用不上,注意有些服务的这个会是空的,导致异常,请先进行判断
ServerArray[i] = info;
}
}
}
}
}
catch (Exception^ e1)
{
//SYS_LOG.Write(__FILE__ + __LINE__ + ":\t" + e1->Message);
System::Windows::Forms::MessageBox::Show(e1->Message, "错误", System::Windows::Forms::MessageBoxButtons::OK,
System::Windows::Forms::MessageBoxIcon::Error);
}
return ServerArray;
}
测试结果: