Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Delphi: WinAPI и системное программирование > Как программно перезапустиь сервис?


Автор: Mephisto 28.5.2007, 16:35
Как программно перезапустиь сервис?

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

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;


Автор: Rennigth 29.5.2007, 17:00
Еще вариант, суть таже, но с проверками всякими, остановом зависимых сервисов и ожиданием старта и останова.
Код мсдн-ский:
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 31.5.2007, 10:02
Исправил несколько ошибок с таймаутами, и обработкой ошибок в выше приведенных функциях:
Код


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;


Автор: E_v_g 8.6.2007, 11:25
А как сделать, чтобы до того, как юзер залогинится, перезапустить сервис? Только написать свой сервис, который его перезапустит? Если да, то как это реализовать?

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

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

Мош лучше после логона проделать с ним что-либо? 

Автор: E_v_g 8.6.2007, 14:31
Цитата

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

Проблема у меня такая: для печати на машине нужно запускать сервис NPrinter, он стоит в автозагрузке, но не запускается. Приходится регистрироваться на машине и руками его запускать. Делать это не всегда возможно, да и лень - идти далеко. smile  В службах для него установлен автозапуск, но он не работает, видимо, зависит от других служб, которые не запущены на момент его старта. Возникла такая мысль - написать сервис, который будет проверять, работает ли NPrinter, и запускать его, если не работает. Сервис - это для того, чтобы стартовал при загрузке ОС. Если можно как-нибудь по-другому, подскажите, please.

Автор: Mephisto 8.6.2007, 14:57
Да можно сделать обычную утилиту которая будет при логоне юзверя запускатся, подключатся к сервису и пытатся его запустить. Если через несколько попыток не получится, то говорить что неасилил... Зачем нужен сервис для этого не пойму.  smile Того кода что выше представлен более чем достаточно!  smile 

Автор: E_v_g 9.6.2007, 05:50
В том все и дело, что она должна запускаться до логона юзера. Т.к. этот юзер может полдня к этой машине не подойти.

Автор: COOLHack 18.2.2008, 18:19
Код моей проги: 

Код

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 подключать?! Или почему так много ошибок? И правельно ли я написал вообще? 

Автор: THandle 18.2.2008, 18:25
COOLHack, ну может все таки стоит хоть какую нибудь книжку почитать? Для начинающих что нибудь, потом Рихтера...

Автор: VICTAR 18.2.2008, 18:29
THandle, +1
Зачем лезть в дебри, если не знаешь основ?

Автор: COOLHack 18.2.2008, 18:32
Ну а может по теме объясните?! 

З.Ы. А книжки я читаю ну не всё же в раз 

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

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

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

Автор: Rennigth 18.2.2008, 18:48
COOLHack, в uses WinSvc добавь

Автор: COOLHack 18.2.2008, 19:07
Строка
Result:=IsServiceRunning;

Ошибка
[Error] Unit1.pas(56): Not enough actual parameters

Автор: COOLHack 18.2.2008, 19:28
Всё, разобрался! Там надо было прописать имя службы

Автор: COOLHack 19.10.2008, 17:22
Блин, не туда запостил... как дулать пост тут??? 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)