unit U_StartServices;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, WinSVC, StdCtrls;

type
  TForm1 = class(TForm)
    btn_StartServices: TButton;
    btn_StopServices: TButton;

    procedure btn_StartServicesClick(Sender: TObject);
    procedure btn_StopServicesClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
function StartServices(const SvrName: string): Boolean;
implementation


{$R *.dfm}

//开启服务

function StartServices(const SvrName: string): Boolean;
var
  SCH, SvcSCH: SC_HANDLE;
  arg: PChar;
  dwStartType: DWORD;
begin
  Result := False;
  SCH := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
  if SCH <= 0 then Exit;
  SvcSCH := OpenService(SCH, PChar(SvrName), SERVICE_ALL_ACCESS);

  if (ChangeServiceConfig(
    SvcSCH, //   handle   of   service
    SERVICE_NO_CHANGE, //SERVICE_NO_CHANGE,   //   service   type:   no   change
    SERVICE_AUTO_START, //   change   service   start   type
    SERVICE_NO_CHANGE, //   error   control:   no   change
    nil, //   binary   path:   no   change
    nil, //   load   order   group:   no   change
    nil, //   tag   ID:   no   change
    nil, //   dependencies:   no   change
    nil, //   account   name:   no   change
    nil, //   password:   no   change
    nil)) then
    showmessage('Auto Start OK')
  else
    showmessage('Auto Start Error');


    if SvcSCH <= 0 then Exit;
  try
    Result := StartService(SvcSCH, 0, arg);
    CloseServiceHandle(SvcSCH);
    CloseServiceHandle(SCH);
  except
    CloseServiceHandle(SvcSCH);
    CloseServiceHandle(SCH);
    Exit;
  end;




end;

//停止服务

function StopServices(const SvrName: string): Boolean;
var
  SCH, SvcSCH: SC_HANDLE;
  SS: TServiceStatus;
begin
  Result := False;
  SCH := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
  if SCH <= 0 then Exit;
  SvcSCH := OpenService(SCH, PChar(SvrName), SERVICE_ALL_ACCESS);
  if SvcSCH <= 0 then Exit;
  try
    Result := ControlService(SvcSCH, SERVICE_CONTROL_STOP, SS);
    CloseServiceHandle(SCH);
    CloseServiceHandle(SvcSCH);
  except
    CloseServiceHandle(SCH);
    CloseServiceHandle(SvcSCH);
    Exit;
  end;
end;


procedure TForm1.btn_StartServicesClick(Sender: TObject);
begin
  if StartServices('PolicyAgent') = true then
    application.MessageBox(PChar('PolicyAgent 服务启动成功'), PChar('服务信息'), MB_ICONINFORMATION)
  else
    application.MessageBox(PChar('PolicyAgent 服务启动失败'), PChar('服务信息'), MB_ICONERROR);
end;

procedure TForm1.btn_StopServicesClick(Sender: TObject);
begin
  if StopServices('PolicyAgent') = true then
    application.MessageBox(PChar('PolicyAgent 服务停止成功'), PChar('服务信息'), MB_ICONINFORMATION)
  else
    application.MessageBox(PChar('PolicyAgent 服务停止成功'), PChar('服务信息'), MB_ICONERROR);
end;

end.
posted on 2011-04-02 16:44  sunjun0427  阅读(1536)  评论(0编辑  收藏  举报