Советы по Delphi

         

Остановка и запуск сервисов


Postmaster предлагает следующий код:

Unit1.dfm

    object Form1: TForm1
Left = 192 Top = 107 Width = 264 Height = 121 Caption = 'Сервис' Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText

Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 2 Top = 8 Width = 67 Height = 13 Caption = 'Имя сервиса' end object Button1: TButton Left = 4 Top = 56 Width = 95 Height = 25 Caption = 'Стоп сервис' TabOrder = 0 OnClick = Button1Click end object Button2: TButton Left = 148 Top = 56 Width = 95 Height = 25 Caption = 'Старт сервис' TabOrder = 1 OnClick = Button2Click end object Edit1: TEdit Left = 0 Top = 24 Width = 241 Height = 21 TabOrder = 2 Text = 'Messenger' end end

Unit1.pas

    unit Unit1;

interface

uses

Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,Winsvc;
type
TForm1 = class(TForm) Button1: TButton; Button2: TButton; Edit1: TEdit; Label1: TLabel; procedure Button1Click(Sender: TObject); procedure StopService(ServiceName: String); procedure Button2Click(Sender: TObject); procedure StartService(ServiceName: String); private { Private declarations } public { Public declarations } end;
var
Form1: TForm1;
implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
StopService(Edit1.Text);
end;

procedure TForm1.StopService(ServiceName: String);
var
schService, schSCManager: DWORD; p: PChar; ss: _SERVICE_STATUS; begin
p:=nil; schSCManager:= OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS); if schSCManager = 0 then RaiseLastWin32Error; try schService:=OpenService(schSCManager,PChar(ServiceName),SERVICE_ALL_ACCESS); if schService = 0 then RaiseLastWin32Error; try if not ControlService(schService,SERVICE_CONTROL_STOP,SS) then  RaiseLastWin32Error; finally CloseServiceHandle(schService); end; finally CloseServiceHandle(schSCManager); end; end;

procedure TForm1.Button2Click(Sender: TObject);
begin
StartService(Edit1.Text);
end;

procedure TForm1.StartService(ServiceName: String);
var
schService, schSCManager: Dword; p: PChar; begin
p:=nil; schSCManager:= OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS); if schSCManager = 0 then RaiseLastWin32Error; try schService:=OpenService(schSCManager,PChar(ServiceName),SERVICE_ALL_ACCESS); if schService = 0 then RaiseLastWin32Error; try if not Winsvc.startService(schService,0,p) then RaiseLastWin32Error; finally CloseServiceHandle(schService); end; finally CloseServiceHandle(schSCManager); end; end;

end.

[001309]



Содержание раздела