求教:Delphi编程的问题,如何在应用程序中开启和关闭windows2000中的服务

解决方案 »

  1.   

    看MSDN Service Functions 
    用ControlService
      

  2.   

    procedure TfrmMenu.StopServiceExecute(Sender: TObject;ServerServiceName:string);
    Var
      SCH: SC_HANDLE;
      SvcSCH: SC_HANDLE;
      ss: TServiceStatus;
    begin
      SCH:= OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
      If SCH=0 then
      Begin
        MessageDlg('Error: OpenSCManager', mtError, [mbOK], 0);
        Exit;
      End;
      Screen.Cursor:= crHourGlass;
      try
        SvcSCH:= OpenService(SCH, PChar(ServerServiceName), SERVICE_ALL_ACCESS);
        If SvcSCH=0 then
        Begin
          MessageDlg('Error: OpenService', mtError, [mbOK], 0);
          Exit;
        End;
        try
          If not ControlService(SvcSCH, SERVICE_CONTROL_STOP, ss) then
          Begin
            Case GetLastError of
               ERROR_ACCESS_DENIED :MessageDlg('The specified handle was not opened with the necessary access.', mtError, [mbOK], 0);
               ERROR_DEPENDENT_SERVICES_RUNNING :MessageDlg('The service cannot be stopped because other running services are dependent on it.', mtError,[mbOK], 0);
               ERROR_INVALID_HANDLE :MessageDlg('The specified handle was not obtained using CreateService or OpenService, or the handle is no longer valid.', mtError, [mbOK], 0);
               ERROR_INVALID_PARAMETER :MessageDlg('The requested control code is undefined.', mtError, [mbOK], 0);
               ERROR_INVALID_SERVICE_CONTROL :MessageDlg('The requested control code is not valid, or it is unacceptable to the service.', mtError,[mbOK], 0);
               ERROR_SERVICE_CANNOT_ACCEPT_CTRL :MessageDlg('The requested control code cannot be sent to the service because the state of the service  is SERVICE_STOPPED, SERVICE_START_PENDING, or SERVICE_STOP_PENDING.',mtError, [mbOK], 0);
               ERROR_SERVICE_NOT_ACTIVE :MessageDlg('The service has not been started.', mtError, [mbOK], 0);
               ERROR_SERVICE_REQUEST_TIMEOUT :MessageDlg('The process for the service was started, but it did not call StartServiceCtrlDispatcher, or the thread that called StartServiceCtrlDispatcher may be blocked in a control handler function.', mtError, [mbOK], 0);
               ERROR_SHUTDOWN_IN_PROGRESS :MessageDlg('The system is shutting down.', mtError, [mbOK], 0);
            Else
               MessageDlg('Error: ControlService', mtError, [mbOK], 0);
            End;
          End;
        finally
          CloseServiceHandle(SvcSCH);
        end;
      finally
        Screen.Cursor:= crDefault;
        CloseServiceHandle(SCH);
      end;
    end;
      

  3.   

    procedure TfrmMenu.StartServiceExecute(Sender: TObject;ServerServiceName:string);
    Var
      SCH: SC_HANDLE;
      SvcSCH: SC_HANDLE;
      ss: TServiceStatus;
    begin
      SCH:= OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
      If SCH=0 then
      Begin
        MessageDlg('Error: OpenSCManager', mtError, [mbOK], 0);
        Exit;
      End;
      Screen.Cursor:= crHourGlass;
      try
        SvcSCH:= OpenService(SCH, PChar(ServerServiceName), SERVICE_ALL_ACCESS);
        If SvcSCH=0 then
        Begin
          MessageDlg('Error: OpenService', mtError, [mbOK], 0);
          Exit;
        End;
        try
          If not ControlService(SvcSCH, SERVICE_CONTROL_START, ss) then
          Begin
            Case GetLastError of
               ERROR_ACCESS_DENIED :MessageDlg('The specified handle was not opened with the necessary access.', mtError, [mbOK], 0);
               ERROR_DEPENDENT_SERVICES_RUNNING :MessageDlg('The service cannot be stopped because other running services are dependent on it.', mtError,[mbOK], 0);
               ERROR_INVALID_HANDLE :MessageDlg('The specified handle was not obtained using CreateService or OpenService, or the handle is no longer valid.', mtError, [mbOK], 0);
               ERROR_INVALID_PARAMETER :MessageDlg('The requested control code is undefined.', mtError, [mbOK], 0);
               ERROR_INVALID_SERVICE_CONTROL :MessageDlg('The requested control code is not valid, or it is unacceptable to the service.', mtError,[mbOK], 0);
               ERROR_SERVICE_CANNOT_ACCEPT_CTRL :MessageDlg('The requested control code cannot be sent to the service because the state of the service  is SERVICE_STOPPED, SERVICE_START_PENDING, or SERVICE_STOP_PENDING.',mtError, [mbOK], 0);
               ERROR_SERVICE_NOT_ACTIVE :MessageDlg('The service has not been started.', mtError, [mbOK], 0);
               ERROR_SERVICE_REQUEST_TIMEOUT :MessageDlg('The process for the service was started, but it did not call StartServiceCtrlDispatcher, or the thread that called StartServiceCtrlDispatcher may be blocked in a control handler function.', mtError, [mbOK], 0);
               ERROR_SHUTDOWN_IN_PROGRESS :MessageDlg('The system is shutting down.', mtError, [mbOK], 0);
            Else
               MessageDlg('Error: ControlService', mtError, [mbOK], 0);
            End;
          End;
        finally
          CloseServiceHandle(SvcSCH);
        end;
      finally
        Screen.Cursor:= crDefault;
        CloseServiceHandle(SCH);
      end;
    end;
      

  4.   

    告诉你个简单办法,直接调用windows命令行
    WinExec('net start mssqlserver', SW_HIDE);          //启动mssqlserver服务
    //其中SW_HIDE表示隐式执行,如果想可见的话换成SW_NORMAL就可以了
    WinExec('net stop mssqlserver', SW_HIDE);           //停止mssqlserver服务
      

  5.   

    谢谢所有热心的朋友!!!我愿请大家喝洒。更感谢zzh(瞌睡),你的办法最简单,最有效。路过贵州时,通知我,一定请你喝酒。
      

  6.   

    支持hch_45(HCH ~ahong.net~)的标准做法。
      

  7.   

    //转贴:以下单元封装了TService的主要方法,对服务程序进行管理
    //你可将它注册为一个控件unit ServiceManager;interface
    uses
      Windows, WinSvc, SvcMgr, Classes;type
      TSMMessageEvent = procedure(Sender : TObject; Message : string) of object;  TServiceManager = class(TComponent)
      private
        fSCMHandle     : THandle;        { Handle to the Service Control Manager       }
        fServiceHandle : THandle;        { Handle to the service                       }
        fMachineName   : string;         { Name of the machine that owns the SCM       }
        fServiceName   : string;         { Name of the service that we're manipulating }
        fServiceStatus : TServiceStatus; { Status of the service                       }
        fOnMessage     : TSMMessageEvent;{ Message event                               }
        fOpened        : boolean;        { currently open?                             }
        function GetMachineName  : string;
        function GetServiceState : integer;
        function GetStateAsString : string;
        function GetIsOpen : boolean;    procedure SendStatus(Msg : string);  public
        property State         : integer read GetServiceState;
        property StateAsString : string  read GetStateAsString;    constructor Create(AOwner : TComponent); override;    function Open : boolean;
        function Close : boolean;
        function Start : boolean;
        function Stop : boolean;
        function Pause : boolean;
        function Continue : boolean;
      published
        property MachineName : string read GetMachineName write fMachineName;
        property ServiceName : string read fServiceName write fServiceName;    property OnMessage   : TSMMessageEvent read fOnMessage write fOnMessage;
        property IsOpen      : boolean read GetIsOpen;
      end; { TServiceMananger }  procedure Register;implementation
    uses
      Forms, Dialogs;constructor TServiceManager.Create(AOwner : TComponent);
    {
      TServiceManager.Create - 01.05.00 - DL  NOTES
        Override constructor  OVERVIEW
        Misc. initialization.
    }
    begin { TServiceManager.Create }
      inherited Create(AOwner);
      MachineName := '';
    end;  { TServiceManager.Create }
    function TServiceManager.GetMachineName : string;
    {
      TServiceManager.GetMachineName - 01.05.00 - DL  NOTES  OVERVIEW
        Retrieve the machine name, if set. If it's NOT set, then
        ask the user.
    }
    begin { TServiceManager.GetMachineName }
      if fMachineName = '' then
        fMachineName := InputBox('Server','Machine name','');  Result := fMachineName;
    end;  { TServiceManager.GetMachineName }function TServiceManager.GetIsOpen : boolean;
    {
      TServiceManager.GetIsOpen - 01.05.00 - DL  NOTES  OVERVIEW
        If the FOpened flag is set and we can get a valid
        state reading from the service, then return TRUE.}
    begin { TServiceManager.GetIsOpen }
      Result := fOpened and (State in [SERVICE_STOPPED,
                          SERVICE_START_PENDING,
                          SERVICE_STOP_PENDING,
                          SERVICE_RUNNING,
                          SERVICE_CONTINUE_PENDING,
                          SERVICE_PAUSE_PENDING,
                          SERVICE_PAUSED]);
    end;  { TServiceManager.GetIsOpen }procedure TServiceManager.SendStatus(Msg : string);
    {
      TServiceManager.SendStatus - 01.05.00 - DL  NOTES  OVERVIEW
        Sends a status message via the OnMessage event.
    }
    begin { TServiceManager.SendStatus }
      if assigned(fOnMessage) then
        fOnMessage(Self,Msg);
    end;  { TServiceManager.SendStatus }
    function TServiceManager.GetStateAsString : string;
    {
      TServiceManager.GetStateAsString - 01.04.00 - DL  NOTES  OVERVIEW
        Returns a string describing the state of the service.}
    begin { TServiceManager.GetStateAsString }
      case GetServiceState of
                 SERVICE_STOPPED : Result := 'The service is not running.';
           SERVICE_START_PENDING : Result := 'The service is starting.';
            SERVICE_STOP_PENDING : Result := 'The service is stopping.';
                 SERVICE_RUNNING : Result := 'The service is running.';
        SERVICE_CONTINUE_PENDING : Result := 'The service continue is pending.';
           SERVICE_PAUSE_PENDING : Result := 'The service pause is pending.';
                  SERVICE_PAUSED : Result := 'The service is paused.';
      else
        Result := 'Unknown state condition';
      end; { case GetServiceState of }  SendStatus(Result);
    end;  { TServiceManager.GetStateAsString }
    function TServiceManager.Start : boolean;
    {
      TServiceMananger.Start - 01.04.00 - DL  Start the service.}
    var
      P : pchar;
    begin { TServiceManager.Start }
      P := '';
      Result := StartService(fServiceHandle,0,p);
      if Result then begin
        while State <> SERVICE_RUNNING do
          Application.ProcessMessages;
        SendStatus('Service started')
      end else
        SendStatus('Service start failed');
    end;  { TServiceManager.Start }function TServiceManager.Stop  : boolean;
    {
      TServiceMananger.Stop - 01.04.00 - DL  Stop the service.}
    begin { TServiceManager.Stop }
      Result := ControlService(fServiceHandle,SERVICE_CONTROL_STOP,fServiceStatus);
      if Result then
        SendStatus('Service stopped')
      else
        SendStatus('Service stop failed');
    end;  { TServiceManager.Stop }function TServiceManager.Pause  : boolean;
    {
      TServiceManager.Pause - 01.04.00 - DL  Pause the service.}
    begin { TServiceManager.Pause }
      Result := ControlService(fServiceHandle,SERVICE_CONTROL_PAUSE,fServiceStatus);
      if Result then
        SendStatus('Service paused')
      else
        SendStatus('Service pause failed');
    end;  { TServiceManager.Pause }function TServiceManager.Continue  : boolean;
    {
      TServiceManager.Continue - 01.04.00 - DL  Continue the service.
    }
    begin { TServiceManager.Continue }
      Result := ControlService(fServiceHandle,SERVICE_CONTROL_CONTINUE,fServiceStatus);
      if Result then
        SendStatus('Service continued')
      else
        SendStatus('Service continue failed');
    end;  { TServiceManager.Continue }
    function TServiceManager.Open : boolean;
    {
      TServiceManager.Open - 01.04.00 - DL  NOTES  OVERVIEW
        Calls OpenSCManager.
    }
    begin { TServiceManager.Open }
      fSCMHandle := OpenSCManager(pchar(MachineName),'ServicesActive',SC_MANAGER_ALL_ACCESS);
      fServiceHandle := OpenService(fscmHandle,pChar(fServiceName),SERVICE_ALL_ACCESS);
      Result := fServiceHandle <> 0;
      if Result then begin
        SendStatus(StateAsString);
        fOpened := TRUE;
      end else begin
        MachineName := '';
        SendStatus('SCM Open failed');
      end;
    end;  { TServiceManager.Open }function TServiceManager.GetServiceState : integer;
    {
      TServiceManager.GetServiceStatus - 01.04.00 - DL  NOTES  OVERVIEW
        Retrieve the status of the service.
    }
    begin { TServiceManager.GetServiceStatus }
      QueryServiceStatus(fServiceHandle,fServiceStatus);
      Result := fServiceStatus.dwCurrentState;
    end;  { TServiceManager.GetServiceStatus }function TServiceManager.Close : boolean;
    {
      TServiceManager.Close - 01.04.00 - DL  Closes the service and SCM.
    }
    begin { TServiceManager.Close }
      Result := CloseServiceHandle(fServiceHandle) and CloseServiceHandle(fSCMHandle);
      if Result then begin
        fOpened := FALSE;
        SendStatus('SCM Closed')
      end else begin
        SendStatus('SCM Close failed');
      end;
    end;  { TServiceManager.Close }procedure Register;
    begin
      RegisterComponents('DLively', [TServiceManager]);
    end;end.
      

  8.   

    这问题Google上有N个解
    问得太多次了
      

  9.   

    http://borland.mblogger.cn/aiirii/category/400.aspx