Delphi 判断系统服务是否运行


本文整理自网络,侵删。

 
//方法1
uses WinSVC;

function isServiceRunning(ServiceName : AnsiString): Boolean;
var
 aServiceControl : SC_Handle;
 aService : SC_Handle;
 status: TServiceStatus;
begin
 Result := False;
 aService := 0;
 aServiceControl := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
 if aServiceControl = 0 then Exit;
 try
   aService := OpenService(aServiceControl, PAnsiChar(ServiceName), SERVICE_QUERY_STATUS);
   if aService = 0 then Exit;
   if not QueryServiceStatus(aService, status)
     then Exit;
   Result := status.dwCurrentState = SERVICE_RUNNING;
 finally
   if aService <> 0 then CloseServiceHandle(aService);
   if aServiceControl <> 0 then CloseServiceHandle(aServiceControl)
 end;
end;

//方法2
uses ActiveX,ComObj;

function isServiceRunning(ServiceName: string): Boolean;
const
 wbemFlagForwardOnly = $00000020;
var
 FSWbemLocator : OLEVariant;
 FWMIService   : OLEVariant;
 FWbemObjectSet: OLEVariant;
 FWbemObject   : OLEVariant;
 oEnum         : IEnumvariant;
 iValue        : LongWord;
begin;
 FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
 FWMIService   := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', '');
 FWbemObjectSet:= FWMIService.ExecQuery('SELECT Name, State FROM Win32_Service WHERE Name="'+ServiceName+'" and State="Running"','WQL',wbemFlagForwardOnly);
 oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
 if oEnum.Next(1, FWbemObject, iValue) = S_OK then
 begin
   Result := True;
   FWbemObject := Unassigned;
 end
 else
   Result := False;
end;

相关阅读 >>

Delphi利用线程注入技术实现刷新流量

Delphi修改默认打印机

Delphi adoconnection断线重连

Delphi程序禁止结束进程

Delphi inttostr 将“整数型”转换成“字符型”

Delphi 获取cpuid的函数

Delphi 取出鼠百标点击的 stringgrid 中某单度元格的值

Delphi 获取鼠标坐标大全方法

tidhttpresponseinfo 中文乱码问题解决

Delphi 实现执行外部程序,并等待程序结束的函数

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...