[求助]如何用DELPHI代码实现打开和关闭服务项~  New

解决方案 »

  1.   

    给你一个启动服务的函数。
    function StartSQLService(ServiceName: PChar): boolean; //参数为服务名
    var
      hSCManager : SC_HANDLE;
      hScSqlServer : SC_HANDLE;
      ScStatus : TServiceStatus;
      WaitCount : Integer;
    begin
      result:=false;
           hSCManager := OpenSCManager( nil, nil, SC_MANAGER_ALL_ACCESS );
      
      if hSCManager=0 then
        begin
        ShowErr(....); //这里自己写吧
        exit;
        end;
      try  hSCSqlServer := OpenService( hSCManager, ServiceName, SERVICE_ALL_ACCESS );
      if hSCSqlServer=0 then
        begin
          ShowErr(...); //这里自己写吧
          exit;
        end;
        try
      StartService( hSCSqlServer, 1, ServiceName );
     
      WaitCount:=0;
      while True do
        begin
          QueryServiceStatus( hSCSqlServer, ScStatus );
            if ScStatus.dwCurrentState = SERVICE_RUNNING then  break;
          Sleep(1000);
          WaitCount := WaitCount + 1;
          if WaitCount=SQLTIMEOUT then
            begin
              ShowErr(...);    //这里自己写吧
              exit;
            end;
        end;
          result:=true;
        finally
      CloseServiceHandle(hSCSqlServer);
        end;
      finally
      CloseServiceHandle(hSCManager);
    end;
    end;