Модераторы: Snowy, bartram, MetalFan, bems, Poseidon, Riply

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Как программно перезапустиь сервис? 
V
    Опции темы
Mephisto
Дата 28.5.2007, 16:35 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Волкъ
***


Профиль
Группа: Завсегдатай
Сообщений: 1818
Регистрация: 27.8.2003
Где: Питер

Репутация: нет
Всего: 34



Как программно перезапустиь сервис?
PM   Вверх
Rouse_
Дата 29.5.2007, 09:20 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 469
Регистрация: 23.4.2005

Репутация: 18
Всего: 29



Проверить - работает ли он, если работает остановить его, потом запустить.
Проверка:
Код

function IsServiceRunning(ServiceName: String): Boolean;
var
  SCManager, Service: SC_HANDLE;
  ServiceStatus: TServiceStatus;
begin
  SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
  if SCManager <> 0 then
  try
    Service := OpenService(SCManager, PChar(ServiceName), SERVICE_QUERY_STATUS);
    if Service <> 0 then
    try
      Result := QueryServiceStatus(Service, ServiceStatus) and
      (ServiceStatus.dwCurrentState = SERVICE_RUNNING);
    finally
      CloseServiceHandle(Service);
    end
    else
      Result := False;
  finally
    CloseServiceHandle(SCManager);
  end
  else
    Result := False;
end;


Остановка:
Код

function ServiceStop(ServiceName: String): Boolean;
var
  SCManager, Service: SC_HANDLE;
  ServiceStatus: TServiceStatus;
begin
  Result := IsServiceRunning;
  if not Result then
  begin
    Result := True;
    Exit;
  end;
  SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
  if SCManager = 0 then
  begin
    ShowMessage(SysErrorMessage(GetLastError));
    Exit;
  end;
  try
    Service := OpenService(SCManager, PChar(ServiceName), SERVICE_STOP);
    if Service = 0 then
    begin
      ShowMessage(SysErrorMessage(GetLastError));
      Exit;
    end;
    try
      if not ControlService(Service, SERVICE_CONTROL_STOP, ServiceStatus)
        and (ServiceStatus.dwCurrentState = SERVICE_STOPPED) then
      begin
        ShowMessage(SysErrorMessage(GetLastError));
        Exit;
      end;
      Result := True;
    finally
      CloseServiceHandle(Service);
    end;
  finally
    CloseServiceHandle(SCManager);
  end;
end;


Запуск:
Код

function ServiceStart(ServiceName: String): Boolean;
var
  SCManager, Service: SC_HANDLE;
  P: PChar;
begin
  Result := False;
  SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
  if SCManager <> 0 then
  try
    Service := OpenService(SCManager, PChar(ServiceName), SERVICE_START);
    if Service <> 0 then
    try
      P := nil;
      Result := StartService(Service, 0, P);
    finally
      CloseServiceHandle(Service);
    end;
  finally
    CloseServiceHandle(SCManager);
  end;
end;




--------------------
 Vae Victis
(Горе побежденным (лат.))
Демо с открытым кодом: http://rouse.drkb.ru 
PM MAIL WWW ICQ   Вверх
Rennigth
Дата 29.5.2007, 17:00 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Участник Клуба
Сообщений: 1708
Регистрация: 21.6.2004
Где: Moscow

Репутация: 8
Всего: 76



Еще вариант, суть таже, но с проверками всякими, остановом зависимых сервисов и ожиданием старта и останова.
Код мсдн-ский:
http://msdn2.microsoft.com/en-us/library/ms686315.aspx
http://msdn2.microsoft.com/en-us/library/ms686335.aspx
переписал на Delphi:

Код

   PServiceStatusProcess = ^TServiceStatusProcess;
  {$EXTERNALSYM _SERVICE_STATUS_PROCESS}
  _SERVICE_STATUS_PROCESS = record
    dwServiceType: DWORD;
    dwCurrentState: DWORD;
    dwControlsAccepted: DWORD;
    dwWin32ExitCode: DWORD;
    dwServiceSpecificExitCode: DWORD;
    dwCheckPoint: DWORD;
    dwWaitHint: DWORD;
    dwProcessId: DWORD;
    dwServiceFlags: DWORD;
  end;
  {$EXTERNALSYM SERVICE_STATUS_PROCESS}
  SERVICE_STATUS_PROCESS = _SERVICE_STATUS_PROCESS;
  TServiceStatusProcess = _SERVICE_STATUS_PROCESS;

const
  SC_STATUS_PROCESS_INFO = 0;
  HEAP_ZERO_MEMORY     = $00000008;

function QueryServiceStatusEx(hService: DWORD; InfoLevel: DWORD; var
  lpServiceStatus: SERVICE_STATUS_PROCESS; cbBufSize: DWORD;
  pcbBytesNeeded: LPDWORD): BOOL; stdcall; external advapi32;


function StopCustomService(hSCM: DWord; hService: DWORD; StopDependencies: BOOL;
  dwTimeout: DWORD): DWORD;
var
  i: Integer;

  ssp: SERVICE_STATUS_PROCESS;
  ss: SERVICE_STATUS;
  ess: _ENUM_SERVICE_STATUS;

  dwStartTime, dwBytesNeeded: DWORD;
  dwCount: DWORD;
  lpDependencies: PEnumServiceStatus;
  hDepService: DWORD;
begin
  dwStartTime := GetTickCount;

   // Make sure the service is not already stopped
  if not QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO,
    ssp, SizeOf(SERVICE_STATUS_PROCESS), @dwTimeout) then
  begin
    Result := GetLastError;
    Exit;
  end;

  if ssp.dwCurrentState = SERVICE_STOPPED then
    Result := ERROR_SUCCESS;

   // If a stop is pending, just wait for it
  while ssp.dwCurrentState = SERVICE_STOP_PENDING do
  begin
    Sleep(ssp.dwWaitHint);
    if not QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO,
      ssp, SizeOf(SERVICE_STATUS_PROCESS), @dwTimeout) then
      Result := GetLastError;

    if ssp.dwCurrentState = SERVICE_STOPPED then
      Result := ERROR_SUCCESS;

    if GetTickCount - dwStartTime > dwTimeout then
      Result := ERROR_TIMEOUT;
  end;

   // If the service is running, dependencies must be stopped first
  if StopDependencies then
  begin
    // Pass a zero-length buffer to get the required buffer size
    if not EnumDependentServices(hService, SERVICE_ACTIVE,
      lpDependencies^, 0, dwBytesNeeded, dwCount) then
         // If the Enum call succeeds, then there are no dependent
         // services so do nothing
      begin
        if GetLastError <> ERROR_MORE_DATA then
          Result := GetLastError; // Unexpected error

         // Allocate a buffer for the dependencies
        lpDependencies := HeapAlloc(GetProcessHeap, HEAP_ZERO_MEMORY, dwBytesNeeded);
        if Assigned(lpDependencies) then
        begin
          try
            // Enumerate the dependencies
            if not EnumDependentServices(hService, SERVICE_ACTIVE,
              lpDependencies^, dwBytesNeeded, dwBytesNeeded, dwCount) then
              Result := GetLastError();

            for i := 0 to dwCount - 1 do
            begin
              lpDependencies := Pointer(Integer(lpDependencies) + i);
              MoveMemory(@ess, lpDependencies, SizeOf(_ENUM_SERVICE_STATUS));

              // Open the service
              hDepService := OpenService(hSCM, ess.lpServiceName,
                 SERVICE_STOP or SERVICE_QUERY_STATUS);

              if hDepService = 0 then
                Result := GetLastError;

              try
                   // Send a stop code
                if not ControlService(hDepService, SERVICE_CONTROL_STOP, ss) then
                  Result := GetLastError;

                  // Wait for the service to stop
                while ss.dwCurrentState <> SERVICE_STOPPED do
                begin
                  Sleep(ssp.dwWaitHint);
                  if not QueryServiceStatusEx(hDepService, SC_STATUS_PROCESS_INFO,
                     ssp, SizeOf(SERVICE_STATUS_PROCESS), @dwBytesNeeded) then
                     Result := GetLastError;

                  if (ssp.dwCurrentState = SERVICE_STOPPED ) then
                     Break;

                  if (GetTickCount() - dwStartTime > dwTimeout ) then
                     Result := ERROR_TIMEOUT;
                end;
              finally
                // Always release the service handle
                CloseServiceHandle( hDepService );
              end;

            end;

          finally
          // Always free the enumeration buffer
            HeapFree( GetProcessHeap, 0, lpDependencies);
          end;

        end else
          Result := GetLastError;
       end;

    end;

   // Send a stop code to the main service
   if not ControlService(hService, SERVICE_CONTROL_STOP, ss) then
      Result := GetLastError;

   // Wait for the service to stop
   while ss.dwCurrentState <> SERVICE_STOPPED do
   begin
     Sleep(ss.dwWaitHint );
     if not QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO,
        ssp, sizeof(SERVICE_STATUS_PROCESS), @dwBytesNeeded) then
        Result := GetLastError;

      if (ssp.dwCurrentState = SERVICE_STOPPED ) then
        Break;

      if GetTickCount() - dwStartTime > dwTimeout then
         Result := ERROR_TIMEOUT;

   end;
   // Return success
   Result := ERROR_SUCCESS;
end;

function StartCustomService(hService: DWORD; dwTimeout: DWORD): DWORD;
var
  ssStatus: SERVICE_STATUS_PROCESS;
  dwOldCheckPoint: DWORD;
  dwStartTickCount: DWORD;
  dwWaitTime: DWORD;
  dwBytesNeeded: DWORD;
  pTmp: PChar;
begin
  pTmp := nil;

  if not StartService(hService, 0, pTmp) then
  begin
    Result := GetLastError;
    Exit;
  end;

    // Check the status until the service is no longer start pending.

  if not QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, ssStatus,
    SizeOf(SERVICE_STATUS_PROCESS), @dwBytesNeeded) then
  begin
    Result := GetLastError;
    Exit;
  end;

    // Save the tick count and initial checkpoint.

  dwStartTickCount := GetTickCount;
  dwOldCheckPoint := ssStatus.dwCheckPoint;

  while ssStatus.dwCurrentState = SERVICE_START_PENDING do
  begin
    dwWaitTime := Round(ssStatus.dwWaitHint / 10);
    if dwWaitTime < 1000 then dwWaitTime := 1000
      else if dwWaitTime > 10000 then dwWaitTime := 10000;

    Sleep(dwWaitTime);

      // Check the status again.

    if not QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO,
      ssStatus, SizeOf(SERVICE_STATUS_PROCESS), @dwBytesNeeded) then
      Break;

    if ssStatus.dwCheckPoint > dwOldCheckPoint then
    begin
          // The service is making progress.
      dwStartTickCount := GetTickCount;
      dwOldCheckPoint := ssStatus.dwCheckPoint;
    end else
      if GetTickCount - dwStartTickCount > dwTimeout then
      begin
            // No progress made within the wait hint
        Result := ERROR_TIMEOUT;
        Break;
      end;
  end;

  Result := ERROR_SUCCESS;
end;


Использовать:
Код

var
  hService, hSCManager: DWORD;
  lMachineName: string;
begin
  lMachineName := GetEnvironmentVariable('COMPUTERNAME');
  hSCManager := OpenSCManager(PChar(lMachineName), SERVICES_ACTIVE_DATABASE, SC_MANAGER_CONNECT);
  if hSCManager > 0 then
  begin
    hService := OpenService(hSCManager, 'FwcAgent', SC_MANAGER_ALL_ACCESS);
    if hService > 0 then
    begin
       if (StopCustomService(hSCManager, hService, False, 10000) <> 0) or
          (StartCustomService(hService, 10000) <> 0) then
         RaiseLastOSError;
      CloseServiceHandle(hService);
    end else
      RaiseLastOSError;
    CloseServiceHandle(hSCManager);
  end else
    RaiseLastOSError;



Это сообщение отредактировал(а) Rennigth - 29.5.2007, 17:03


--------------------
(* Honesta mors turpi vita potior *)
PM MAIL ICQ   Вверх
Rennigth
Дата 31.5.2007, 10:02 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Участник Клуба
Сообщений: 1708
Регистрация: 21.6.2004
Где: Moscow

Репутация: 8
Всего: 76



Исправил несколько ошибок с таймаутами, и обработкой ошибок в выше приведенных функциях:
Код


function StartCustomService(hService: DWORD; dwTimeout: DWORD): DWORD;
var
  ssStatus: SERVICE_STATUS_PROCESS;
  dwOldCheckPoint: DWORD;
  dwStartTickCount: DWORD;
  dwWaitTime: DWORD;
  dwBytesNeeded: DWORD;
  pTmp: PChar;
begin
  pTmp := nil;

  if not StartService(hService, 0, pTmp) then
  begin
    Result := GetLastError;
    Exit;
  end;

    // Check the status until the service is no longer start pending.

  if not QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, ssStatus,
    SizeOf(SERVICE_STATUS_PROCESS), @dwBytesNeeded) then
  begin
    Result := GetLastError;
    Exit;
  end;

    // Save the tick count and initial checkpoint.

  dwStartTickCount := GetTickCount;
  dwOldCheckPoint := ssStatus.dwCheckPoint;

  while ssStatus.dwCurrentState = SERVICE_START_PENDING do
  begin
    dwWaitTime := Round(ssStatus.dwWaitHint / 10);
    if dwWaitTime < 1000 then dwWaitTime := 1000
      else if dwWaitTime > 10000 then dwWaitTime := 10000;

    Sleep(dwWaitTime);

      // Check the status again.

    if not QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO,
      ssStatus, SizeOf(SERVICE_STATUS_PROCESS), @dwBytesNeeded) then
    begin
      Result := GetLastError;
      Exit;
    end;

    if ssStatus.dwCheckPoint > dwOldCheckPoint then
    begin
          // The service is making progress.
      dwStartTickCount := GetTickCount;
      dwOldCheckPoint := ssStatus.dwCheckPoint;
    end else
      if GetTickCount - dwStartTickCount > dwTimeout then
      begin
            // No progress made within the wait hint
        Result := ERROR_TIMEOUT;
        Exit;
      end;
  end;

  Result := ERROR_SUCCESS;
end;

function StopCustomService(hSCM: DWord; hService: DWORD; StopDependencies: BOOL;
  dwTimeout: DWORD): DWORD;
var
  i: Integer;

  ssp: SERVICE_STATUS_PROCESS;
  ss: SERVICE_STATUS;
  ess: _ENUM_SERVICE_STATUS;

  dwStartTime, dwBytesNeeded, dwWaitTime: DWORD;
  dwCount: DWORD;
  lpDependencies: PEnumServiceStatus;
  hDepService: DWORD;
begin
  dwStartTime := GetTickCount;

   // Make sure the service is not already stopped
  if not QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO,
    ssp, SizeOf(SERVICE_STATUS_PROCESS), @dwTimeout) then
  begin
    Result := GetLastError;
    Exit;
  end;

  if ssp.dwCurrentState = SERVICE_STOPPED then
  begin
    Result := ERROR_SUCCESS;
    Exit;
  end;

   // If a stop is pending, just wait for it
  while ssp.dwCurrentState = SERVICE_STOP_PENDING do
  begin
    dwWaitTime := Round(ssp.dwWaitHint / 10);
    if dwWaitTime < 1000 then dwWaitTime := 1000
      else if dwWaitTime > 10000 then dwWaitTime := 10000;

    Sleep(dwWaitTime);
    if not QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO,
      ssp, SizeOf(SERVICE_STATUS_PROCESS), @dwTimeout) then
    begin
      Result := GetLastError;
      Exit;
    end;

    if ssp.dwCurrentState = SERVICE_STOPPED then
    begin
      Result := ERROR_SUCCESS;
      Exit;
    end;

    if GetTickCount - dwStartTime > dwTimeout then
    begin
      Result := ERROR_TIMEOUT;
      Exit;
    end;
  end;

   // If the service is running, dependencies must be stopped first
  if StopDependencies then
  begin
//    lpDependencies := nil;
    dwBytesNeeded := 0;
    // Pass a zero-length buffer to get the required buffer size
    if not EnumDependentServices(hService, SERVICE_ACTIVE,
      lpDependencies^, 0, dwBytesNeeded, dwCount) then
    begin
     // If the Enum call succeeds, then there are no dependent
     // services so do nothing
      if GetLastError <> ERROR_MORE_DATA then
      begin
        Result := GetLastError; // Unexpected error
        Exit;
      end;

       // Allocate a buffer for the dependencies
      lpDependencies := HeapAlloc(GetProcessHeap, HEAP_ZERO_MEMORY, dwBytesNeeded);
      if Assigned(lpDependencies) then
      begin
        try
          // Enumerate the dependencies
          if not EnumDependentServices(hService, SERVICE_ACTIVE,
              lpDependencies^, dwBytesNeeded, dwBytesNeeded, dwCount) then
              Result := GetLastError();

            for i := 0 to dwCount - 1 do
            begin
              lpDependencies := Pointer(Integer(lpDependencies) + i);
              MoveMemory(@ess, lpDependencies, SizeOf(_ENUM_SERVICE_STATUS));

              // Open the service
              hDepService := OpenService(hSCM, ess.lpServiceName,
                SERVICE_STOP or SERVICE_QUERY_STATUS);

              if hDepService > 0 then
              begin
                try
                     // Send a stop code
                  if ControlService(hDepService, SERVICE_CONTROL_STOP, ss) then
                    // Wait for the service to stop
                    while ss.dwCurrentState <> SERVICE_STOPPED do
                    begin

                      dwWaitTime := Round(ssp.dwWaitHint / 10);
                      if dwWaitTime < 1000 then dwWaitTime := 1000
                        else if dwWaitTime > 10000 then dwWaitTime := 10000;
                      Sleep(dwWaitTime);

                      if not QueryServiceStatusEx(hDepService, SC_STATUS_PROCESS_INFO,
                         ssp, SizeOf(SERVICE_STATUS_PROCESS), @dwBytesNeeded) then
                       begin
                         Result := GetLastError;
                         CloseServiceHandle( hDepService );
                         Exit;
                       end;

                      if (ssp.dwCurrentState = SERVICE_STOPPED) then
                         Break;

                      if (GetTickCount - dwStartTime > dwTimeout) then
                      begin
                         Result := ERROR_TIMEOUT;
                         CloseServiceHandle( hDepService );
                         Exit;
                      end;
                    end;

                finally
                  // Always release the service handle
                  CloseServiceHandle( hDepService );
                end;

              end;
            end;

          finally
          // Always free the enumeration buffer
            HeapFree( GetProcessHeap, 0, lpDependencies);
          end;

        end else begin
          Result := GetLastError;
          Exit
        end;
      end;

  end;

 // Send a stop code to the main service
  if not ControlService(hService, SERVICE_CONTROL_STOP, ss) then
  begin
    Result := GetLastError;
    Exit;
  end;

  // Wait for the service to stop
  while ss.dwCurrentState <> SERVICE_STOPPED do
  begin
    dwWaitTime := Round(ss.dwWaitHint / 10);
    if dwWaitTime < 1000 then dwWaitTime := 1000
      else if dwWaitTime > 10000 then dwWaitTime := 10000;
    Sleep(dwWaitTime);

    if not QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO,
      ssp, sizeof(SERVICE_STATUS_PROCESS), @dwBytesNeeded) then
    begin
      Result := GetLastError;
      Exit;
    end;

    if (ssp.dwCurrentState = SERVICE_STOPPED) then
      Break;

    if GetTickCount - dwStartTime > dwTimeout then
    begin
      Result := ERROR_TIMEOUT;
      Exit;
    end;
  end;

   // Return success
  Result := ERROR_SUCCESS;
end;

function RestartCustomService(hSCM: DWord; hService: DWORD; StopDependencies: BOOL;
  dwTimeout: DWORD): DWORD;
begin
  Result := StopCustomService(hSCM, hService, StopDependencies, dwTimeout);
  if Result = ERROR_SUCCESS then
    Result := StartCustomService(hService, dwTimeout);
end;




--------------------
(* Honesta mors turpi vita potior *)
PM MAIL ICQ   Вверх
E_v_g
Дата 8.6.2007, 11:25 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 76
Регистрация: 15.11.2006

Репутация: нет
Всего: нет



А как сделать, чтобы до того, как юзер залогинится, перезапустить сервис? Только написать свой сервис, который его перезапустит? Если да, то как это реализовать?
PM ICQ   Вверх
Mephisto
Дата 8.6.2007, 13:40 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Волкъ
***


Профиль
Группа: Завсегдатай
Сообщений: 1818
Регистрация: 27.8.2003
Где: Питер

Репутация: нет
Всего: 34



Цитата(E_v_g @  8.6.2007,  12:25 Найти цитируемый пост)
Если да, то как это реализовать? 

Просто перезапустить. А вообще странное желание.  smile 

Мош лучше после логона проделать с ним что-либо? 
PM   Вверх
E_v_g
Дата 8.6.2007, 14:31 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 76
Регистрация: 15.11.2006

Репутация: нет
Всего: нет



Цитата

А вообще странное желание.   

Проблема у меня такая: для печати на машине нужно запускать сервис NPrinter, он стоит в автозагрузке, но не запускается. Приходится регистрироваться на машине и руками его запускать. Делать это не всегда возможно, да и лень - идти далеко. smile  В службах для него установлен автозапуск, но он не работает, видимо, зависит от других служб, которые не запущены на момент его старта. Возникла такая мысль - написать сервис, который будет проверять, работает ли NPrinter, и запускать его, если не работает. Сервис - это для того, чтобы стартовал при загрузке ОС. Если можно как-нибудь по-другому, подскажите, please.
PM ICQ   Вверх
Mephisto
Дата 8.6.2007, 14:57 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Волкъ
***


Профиль
Группа: Завсегдатай
Сообщений: 1818
Регистрация: 27.8.2003
Где: Питер

Репутация: нет
Всего: 34



Да можно сделать обычную утилиту которая будет при логоне юзверя запускатся, подключатся к сервису и пытатся его запустить. Если через несколько попыток не получится, то говорить что неасилил... Зачем нужен сервис для этого не пойму.  smile Того кода что выше представлен более чем достаточно!  smile 
PM   Вверх
E_v_g
Дата 9.6.2007, 05:50 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 76
Регистрация: 15.11.2006

Репутация: нет
Всего: нет



В том все и дело, что она должна запускаться до логона юзера. Т.к. этот юзер может полдня к этой машине не подойти.
PM ICQ   Вверх
COOLHack
Дата 18.2.2008, 18:19 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 281
Регистрация: 8.2.2008

Репутация: -1
Всего: 0



Код моей проги: 

Код

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function IsServiceRunning(ServiceName: String): Boolean;
var
  SCManager, Service: SC_HANDLE;
  ServiceStatus: TServiceStatus;
begin
  SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
  if SCManager <> 0 then
  try
    Service := OpenService(SCManager, PChar(ServiceName), SERVICE_QUERY_STATUS);
    if Service <> 0 then
    try
      Result := QueryServiceStatus(Service, ServiceStatus) and
      (ServiceStatus.dwCurrentState = SERVICE_RUNNING);
    finally
      CloseServiceHandle(Service);
    end
    else
      Result := False;
  finally
    CloseServiceHandle(SCManager);
  end
  else
    Result := False;
end;

function ServiceStop(ServiceName: String): Boolean;
var
  SCManager, Service: SC_HANDLE;
  ServiceStatus: TServiceStatus;
begin
  Result := IsServiceRunning;
  if not Result then
  begin
    Result := True;
    Exit;
  end;
  SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
  if SCManager = 0 then
  begin
    ShowMessage(SysErrorMessage(GetLastError));
    Exit;
  end;
  try
    Service := OpenService(SCManager, PChar(ServiceName), SERVICE_STOP);
    if Service = 0 then
    begin
      ShowMessage(SysErrorMessage(GetLastError));
      Exit;
    end;
    try
      if not ControlService(Service, SERVICE_CONTROL_STOP, ServiceStatus)
        and (ServiceStatus.dwCurrentState = SERVICE_STOPPED) then
      begin
        ShowMessage(SysErrorMessage(GetLastError));
        Exit;
      end;
      Result := True;
    finally
      CloseServiceHandle(Service);
    end;
  finally
    CloseServiceHandle(SCManager);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
ServiceStop('Apache2')
end;

end.



Ошибки при компиляции: 
Код

[Error] Unit1.pas(28): Undeclared identifier: 'SC_HANDLE'
[Error] Unit1.pas(29): Undeclared identifier: 'TServiceStatus'
[Error] Unit1.pas(31): Undeclared identifier: 'OpenSCManager'
[Error] Unit1.pas(31): Undeclared identifier: 'SC_MANAGER_ALL_ACCESS'
[Warning] Unit1.pas(32): Comparing signed and unsigned types - widened both operands
[Error] Unit1.pas(34): Undeclared identifier: 'OpenService'
[Error] Unit1.pas(34): Undeclared identifier: 'SERVICE_QUERY_STATUS'
[Warning] Unit1.pas(35): Comparing signed and unsigned types - widened both operands
[Error] Unit1.pas(37): Undeclared identifier: 'QueryServiceStatus'
[Error] Unit1.pas(38): ')' expected but identifier 'dwCurrentState' found
[Error] Unit1.pas(38): ':=' expected but '=' found
[Error] Unit1.pas(38): EXCEPT or FINALLY expected
[Error] Unit1.pas(41): EXCEPT or FINALLY expected
[Error] Unit1.pas(44): 'END' expected but 'FINALLY' found
[Error] Unit1.pas(47): ';' expected but 'ELSE' found
[Error] Unit1.pas(49): '.' expected but ';' found
[Error] Unit1.pas(53): Undeclared identifier: 'SC_HANDLE'
[Error] Unit1.pas(54): Undeclared identifier: 'TServiceStatus'
[Error] Unit1.pas(56): Not enough actual parameters
[Error] Unit1.pas(62): Undeclared identifier: 'OpenSCManager'
[Error] Unit1.pas(62): Undeclared identifier: 'SC_MANAGER_ALL_ACCESS'
[Warning] Unit1.pas(63): Comparing signed and unsigned types - widened both operands
[Error] Unit1.pas(69): Undeclared identifier: 'OpenService'
[Error] Unit1.pas(69): Undeclared identifier: 'SERVICE_STOP'
[Warning] Unit1.pas(70): Comparing signed and unsigned types - widened both operands
[Error] Unit1.pas(76): Undeclared identifier: 'ControlService'
[Error] Unit1.pas(76): Undeclared identifier: 'SERVICE_CONTROL_STOP'
[Error] Unit1.pas(77): ')' expected but identifier 'dwCurrentState' found
[Error] Unit1.pas(84): Undeclared identifier: 'CloseServiceHandle'
[Fatal Error] Project1.dpr(5): Could not compile used unit 'Unit1.pas'


Что надо в uses подключать?! Или почему так много ошибок? И правельно ли я написал вообще? 

PM MAIL   Вверх
THandle
Дата 18.2.2008, 18:25 (ссылка) |    (голосов:1) Загрузка ... Загрузка ... Быстрая цитата Цитата


Хранитель Клуба
Group Icon
Награды: 1



Профиль
Группа: Админ
Сообщений: 3639
Регистрация: 31.7.2007
Где: Moscow, Dubai

Репутация: 7
Всего: 372



COOLHack, ну может все таки стоит хоть какую нибудь книжку почитать? Для начинающих что нибудь, потом Рихтера...
PM   Вверх
VICTAR
Дата 18.2.2008, 18:29 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Участник
Сообщений: 1108
Регистрация: 6.10.2006

Репутация: нет
Всего: 80



THandle, +1
Зачем лезть в дебри, если не знаешь основ?
PM MAIL   Вверх
COOLHack
Дата 18.2.2008, 18:32 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 281
Регистрация: 8.2.2008

Репутация: -1
Всего: 0



Ну а может по теме объясните?! 

З.Ы. А книжки я читаю ну не всё же в раз 
PM MAIL   Вверх
THandle
Дата 18.2.2008, 18:36 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Хранитель Клуба
Group Icon
Награды: 1



Профиль
Группа: Админ
Сообщений: 3639
Регистрация: 31.7.2007
Где: Moscow, Dubai

Репутация: 7
Всего: 372



Цитата(COOLHack @  18.2.2008,  18:32 Найти цитируемый пост)
З.Ы. А книжки я читаю ну не всё же в раз  

Вот именно. Сначала делай что нибудь попроще а потом уже во все это лезь.

Тебе главное что? Скопировать код который тебе дадут в инете, или самому понять?


Это сообщение отредактировал(а) THandle - 18.2.2008, 18:37
PM   Вверх
Rennigth
Дата 18.2.2008, 18:48 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Участник Клуба
Сообщений: 1708
Регистрация: 21.6.2004
Где: Moscow

Репутация: 8
Всего: 76



COOLHack, в uses WinSvc добавь


--------------------
(* Honesta mors turpi vita potior *)
PM MAIL ICQ   Вверх
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Delphi: WinAPI и системное программирование"
Snowybartram
MetalFanbems
PoseidonRrader
Riply

Запрещено:

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Литературу по Delphi обсуждаем здесь
  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы по реализации алгоритмов рассматриваются здесь
  • 90% ответов на свои вопросы можно найти в DRKB (Delphi Russian Knowledge Base) - крупнейшем в рунете сборнике материалов по Дельфи
  • 99% ответов по WinAPI можно найти в MSDN Library, оставшиеся 1% здесь

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Snowy, bartram, MetalFan, bems, Poseidon, Rrader, Riply.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Delphi: WinAPI и системное программирование | Следующая тема »


 




[ Время генерации скрипта: 0.1050 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.