服务管理器
根据描述搜索服务
引言
本文将展示如何获取具有特定描述的系统服务列表。
背景
我见过很多文章介绍如何安装、卸载、启动和停止服务,但在服务管理器中,我(在朋友 Yogi 的帮助下)添加了一个额外的功能,即获取满足特定描述的系统服务列表。
描述
.NET Framework 提供了 System.ServiceProcess
命名空间。在这个命名空间中,你会找到一个 SystemController
类。这个类有一个 static
方法 GetServices()
,它返回一个 SystemController
对象数组,其中包含系统上运行的所有服务。
ServiceController[] _serviceControllers;
_serviceControllers=ServiceController.GetServices();
使用 OpenSCManager
打开服务数据库
IntPtr sc_handle = OpenSCManager(null,null,(int)SCM_ACCESS.SC_MANAGER_ALL_ACCESS);
打开并查询服务的描述
public static string[] GetServices(string filterOnDescription)
{
ServiceController[] _serviceControllers;
_serviceControllers=ServiceController.GetServices();
string[] _serviceList = null;
System.Collections.ArrayList _arrayList = new System.Collections.ArrayList();
IntPtr sc_handle = OpenSCManager(null,null,(int)SCM_ACCESS.SC_MANAGER_ALL_ACCESS);
if (sc_handle.ToInt32() != 0)
{
IntPtr serviceHandle;
SERVICE_DESCRIPTION descriptionStruct = new SERVICE_DESCRIPTION();
for (int i=0;i<_serviceControllers.Length;i++)
{
UInt32 dwBytesNeeded;
serviceHandle = OpenService
( sc_handle, _serviceControllers[i].ServiceName,
SERVICE_QUERY_CONFIG );
if ( serviceHandle != IntPtr.Zero )
{
// Determine the buffer size needed
bool success = QueryServiceConfig2( serviceHandle,
SERVICE_CONFIG_DESCRIPTION, IntPtr.Zero, 0, out dwBytesNeeded );
IntPtr ptr = Marshal.AllocHGlobal((int)dwBytesNeeded);
success = QueryServiceConfig2( serviceHandle,
SERVICE_CONFIG_DESCRIPTION, ptr,
dwBytesNeeded, out dwBytesNeeded );
Marshal.PtrToStructure(ptr, descriptionStruct);
Marshal.FreeHGlobal(ptr);
if((descriptionStruct.lpDescription != null) && (
descriptionStruct.lpDescription.IndexOf(filterOnDescription)!=-1))
_arrayList.Add(_serviceControllers[i].ServiceName);
}
}
if(_arrayList.Count > 0)
_serviceList = (string[])_arrayList.ToArray(typeof(string));
return _serviceList;
}
else
{
return null;
}
}
历史
- 2008年6月9日:初始发布