Delphi如何获取系统服务(即Service服务程序)列表

来源:互联网 发布:php转盘抽奖源码 编辑:程序博客网 时间:2024/04/28 00:00
[delphi] view plain copy
 print?
  1. procedure TDpModel.ServiceNames(Names: TStrings; DisplayNames: TStrings = nil;  
  2.   const Service_Type: integer = $30const Computer: PChar = nil);  
  3. { 
  4.   返回系统服务列表,Names:用于接收返回的服务名称列表, 
  5.   DisplayName:用于接收返回的对应显示名称列表, 
  6.   uType:需要返回那些类型服务名称列表,可以为SERVICE_DRIVER,SERVICE_WIN32,SERVICE_ALL 
  7. }  
  8. type  
  9.   TEnumServices = array[0..0of TEnumServiceStatus;  //windows API结构体  
  10.   PEnumServices = ^TEnumServices;  //声明类指针  
  11. var  
  12.   SCM: SC_Handle;  
  13.   Services: PEnumServices; //定义结构体  
  14.   Len: Cardinal; //无符号32位整数 ,取值0到4294967295范围。  
  15.   ServiceCount, ResumeHandle, i: Cardinal;  
  16. begin  
  17.   ResumeHandle := 0;  
  18.   
  19.   //建立了一个连接到服务控制管理器的句柄,并打开指定的数据库。  
  20.   SCM := OpenSCManager(Computer, nil, SC_MANAGER_ALL_ACCESS);  
  21.   { 
  22.      Computer:计算机标示指针,如果该指针为NULL ,或者如果它指向一个空字符串, 
  23.       则连接到本地计算机上的服务控制管理器。 
  24.      nil:如果该指针为NULL ,默认打开ServicesActive数据库。 
  25.      SC_MANAGER_ALL_ACCESS:指定访问服务的权限。 
  26.   }  
  27.   Len := 0;  
  28.   ServiceCount := 0;  
  29.   Services := nil;  
  30.   try  
  31.     Names.BeginUpdate;  
  32.     //判断DisplayNames是否为空  
  33.     if Assigned(DisplayNames) then DisplayNames.BeginUpdate;  
  34.   
  35.     if SCM <> 0 then  
  36.     begin  
  37.       //枚举当前系统服务,详见MSDN  
  38.       EnumServicesStatus(SCM, SERVICE_DRIVER or SERVICE_WIN32, SERVICE_STATE_ALL,  
  39.         Services[0], 0, Len, ServiceCount, ResumeHandle);  
  40.       GetMem(Services, Len);  
  41.       EnumServicesStatus(SCM, SERVICE_DRIVER or SERVICE_WIN32, SERVICE_STATE_ALL,  
  42.         Services[0], Len, Len, ServiceCount, ResumeHandle);  
  43.   
  44.       //Tstring赋值  
  45.       Names.Add(IntToStr(ServiceCount));  
  46.   
  47.       //循环遍历服务  
  48.       for i := 0 to ServiceCount - 1 do  
  49.       begin  
  50.         Names.Add(Services[i].lpServiceName);  
  51.         if Assigned(DisplayNames) then  
  52.         begin  
  53.           DisplayNames.Add(Services[i].lpDisplayName);  
  54.         end;  
  55.   
  56.       end;  
  57.       FreeMem(Services);  
  58.     end;  
  59.   finally  
  60.     Names.EndUpdate;  
  61.     if Assigned(DisplayNames) then DisplayNames.EndUpdate;  
  62.     CloseServiceHandle(SCM);  
  63.   end;  
  64. end;  
0 0
原创粉丝点击