请教:
   怎么样使用  API函数 来创建 系统服务,并实现安装 启动 停止功能??

解决方案 »

  1.   

    给你个参考,希望能有用用Delphi创建服务程序
    http://www.programbbs.com/doc/379.htm使用Dos命令,注册启动Delphi服务程序
    运行——CMD——到程序所在目录下
    假定服务程序名称my
    my.exe /install 注册
    net start 名称  启动
    net stop名称  停止
      

  2.   

    hService := CreateService(
          hSCManager,
          '服务名',
          '服务名',
          SERVICE_START,
          SERVICE_KERNEL_DRIVER,
          SERVICE_DEMAND_START,
          SERVICE_ERROR_IGNORE,
          lpFileName,
          nil,
          nil,
          nil,
          nil,
          nil
          );
      

  3.   

    {
      The following class TServiceManager can be used to manage your NT-Services.
      You can do things like start, stop, pause or querying a services status.
    }{
      Die folgende Klasse TServiceManager kann verwendet werden, um NT-Dienste
      zu verwalten. Hierbei gibt es Funktionen wie Start, Stop, Pause sowie
      Statusabfragen.
    }
    //  Thanks for this one to Frederik Schaller as well - it's a co-work }unit ServiceManager;interfaceuses
      SysUtils, Windows, WinSvc;type  TServiceManager = class
      private
        { Private declarations }
        ServiceControlManager: SC_Handle;
        ServiceHandle: SC_Handle;
      protected
        function DoStartService(NumberOfArgument: DWORD; ServiceArgVectors: PChar): Boolean;
      public
        { Public declarations }
        function Connect(MachineName: PChar = nil; DatabaseName: PChar = nil;
          Access: DWORD = SC_MANAGER_ALL_ACCESS): Boolean;  // Access may be SC_MANAGER_ALL_ACCESS
        function OpenServiceConnection(ServiceName: PChar): Boolean;
        function StartService: Boolean; overload; // Simple start
        function StartService(NumberOfArgument: DWORD; ServiceArgVectors: PChar): Boolean;
          overload; // More complex start
        function StopService: Boolean;
        procedure PauseService;
        procedure ContinueService;
        procedure ShutdownService;
        procedure DisableService;
        function GetStatus: DWORD;
        function ServiceRunning: Boolean;
        function ServiceStopped: Boolean;
      end;implementation{ TServiceManager }function TServiceManager.Connect(MachineName, DatabaseName: PChar;
      Access: DWORD): Boolean;
    begin
      { open a connection to the windows service manager }
      ServiceControlManager := OpenSCManager(MachineName, DatabaseName, Access);
      Result := (ServiceControlManager <> 0);
    end;
    function TServiceManager.OpenServiceConnection(ServiceName: PChar): Boolean;
    begin
      { open a connetcion to a specific service }
      ServiceHandle := OpenService(ServiceControlManager, ServiceName, SERVICE_ALL_ACCESS);
      Result := (ServiceHandle <> 0);
    end;procedure TServiceManager.PauseService;
    var
      ServiceStatus: TServiceStatus;
    begin
      { Pause the service: attention not supported by all services }
      ControlService(ServiceHandle, SERVICE_CONTROL_PAUSE, ServiceStatus);
    end;function TServiceManager.StopService: Boolean;
    var
      ServiceStatus: TServiceStatus;
    begin
      { Stop the service }
      Result := ControlService(ServiceHandle, SERVICE_CONTROL_STOP, ServiceStatus);
    end;procedure TServiceManager.ContinueService;
    var
      ServiceStatus: TServiceStatus;
    begin
      { Continue the service after a pause: attention not supported by all services }
      ControlService(ServiceHandle, SERVICE_CONTROL_CONTINUE, ServiceStatus);
    end;procedure TServiceManager.ShutdownService;
    var
      ServiceStatus: TServiceStatus;
    begin
      { Shut service down: attention not supported by all services }
      ControlService(ServiceHandle, SERVICE_CONTROL_SHUTDOWN, ServiceStatus);
    end;function TServiceManager.StartService: Boolean;
    begin
      Result := DoStartService(0, '');
    end;function TServiceManager.StartService(NumberOfArgument: DWORD;
      ServiceArgVectors: PChar): Boolean;
    begin
      Result := DoStartService(NumberOfArgument, ServiceArgVectors);
    end;function TServiceManager.GetStatus: DWORD;
    var
      ServiceStatus: TServiceStatus;
    begin
    { Returns the status of the service. Maybe you want to check this
      more than once, so just call this function again.
      Results may be: SERVICE_STOPPED
                      SERVICE_START_PENDING
                      SERVICE_STOP_PENDING
                      SERVICE_RUNNING
                      SERVICE_CONTINUE_PENDING
                      SERVICE_PAUSE_PENDING
                      SERVICE_PAUSED   }
      QueryServiceStatus(ServiceHandle, ServiceStatus);
      Result := ServiceStatus.dwCurrentState;
    end;procedure TServiceManager.DisableService;
    begin
      { Implementation is following... }
    end;function TServiceManager.ServiceRunning: Boolean;
    begin
      Result := (GetStatus = SERVICE_RUNNING);
    end;function TServiceManager.ServiceStopped: Boolean;
    begin
      Result := (GetStatus = SERVICE_STOPPED);
    end;function TServiceManager.DoStartService(NumberOfArgument: DWORD;
      ServiceArgVectors: PChar): Boolean;
    begin
      Result := WinSvc.StartService(ServiceHandle, NumberOfArgument, ServiceArgVectors);
    end;end.
    http://www.koders.com/delphi/fidA93FC2FB49EF3AF452264065040CB865BEE563A5.aspx
      

  4.   

    1打开服务管理器OpenSCManager
    2创建服务CreateService
    3关闭服务句柄CloseServiceHandle网上有相关的函数可以调用
      

  5.   

    program project1;uses
      windows, Messages, ShellApi, WinSvc,SvcMgr, SysUtils;{$R *.res}
    const
       id_Button1 = 100;
       id_Button2 = 200;
       id_Button3 = 300;
       id_Button4 = 400;
       id_Button5 = 500;
       id_Button6 = 600;
       Qidong  = 7 ;
       Tingzhi = 8 ;
       Xiezai  = 9 ;
       ServiceName = 'AServerTest';var
      Status: TServiceStatus;
      StatusHandle: SERVICE_STATUS_HANDLE;
      ServiceTable: array [0..1] of TServiceTableEntry; 
      Stopped: boolean;
      Paused: boolean;//服务入口程序:
    procedure ServiceMain;
    begin
      repeat
      if not Paused then 
      begin 
        Sleep(100000);
      end; 
      until Stopped;
    end;//服务控制:
    procedure ServiceCtrlHandler(Control: dword); stdcall;
    begin
      case Control of
        SERVICE_CONTROL_STOP:
        begin 
          Stopped := True; 
          Status.dwCurrentState := SERVICE_STOP_PENDING; 
          SetServiceStatus(StatusHandle, Status);
        end; 
        SERVICE_CONTROL_PAUSE:
        begin
          Paused := True;
          Status.dwcurrentstate := SERVICE_PAUSED;
          SetServiceStatus(StatusHandle, Status);
        end;
        SERVICE_CONTROL_CONTINUE:
        begin
          Paused := False;
          Status.dwCurrentState := SERVICE_RUNNING;
          SetServiceStatus(StatusHandle, Status);
        end;
        SERVICE_CONTROL_INTERROGATE: SetServiceStatus(StatusHandle, Status);
        SERVICE_CONTROL_SHUTDOWN: Stopped := True; 
      end;
    end;//服务分配:
    procedure ServiceCtrlDispatcher(dwArgc: dword; var lpszArgv: pchar); stdcall;
    begin
      StatusHandle := RegisterServiceCtrlHandler(ServiceName, @ServiceCtrlHandler);
      if StatusHandle <> 0 then
      begin
        ZeroMemory(@Status, SizeOf(Status));
        Status.dwServiceType := SERVICE_WIN32_OWN_PROCESS or SERVICE_INTERACTIVE_PROCESS;
        Status.dwCurrentState:= SERVICE_START_PENDING;
        Status.dwControlsAccepted := SERVICE_ACCEPT_STOP or SERVICE_ACCEPT_PAUSE_CONTINUE;
        Status.dwWaitHint := 1000;
        SetServiceStatus(StatusHandle, Status);
        Stopped := False;
        Paused := False;
        Status.dwCurrentState := SERVICE_RUNNING;
        SetServiceStatus(StatusHandle, Status);
        ServiceMain; //调用主程序
        Status.dwCurrentState := SERVICE_STOPPED;
        SetServiceStatus(StatusHandle, Status);
      end;
    end;//控制服务: 启动   停止  卸载
    procedure AControlService(ServiceName: pchar; Mark: UINT);
    var
      SCManager: SC_HANDLE;
      Service: SC_HANDLE;
    begin
      SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
      if SCManager = 0 then Exit;
      try
        Service := OpenService(SCManager, ServiceName, SERVICE_ALL_ACCESS);    case Mark of
         Xiezai:
           begin
             ControlService(Service, SERVICE_CONTROL_STOP, Status);
             DeleteService(Service);
           end ;
         Tingzhi:
            ControlService(Service, SERVICE_CONTROL_STOP, Status);
         Qidong:
            ControlService(Service, SERVICE_CONTROL_CONTINUE, Status);
        end;
        CloseServiceHandle(Service);
      finally
        CloseServiceHandle(SCManager);
      end;
    end;//安装启动服务:
    procedure InstallService(ServiceName, DisplayName: pchar; FileName: string);
    var
      SCManager: SC_HANDLE;
      Service: SC_HANDLE;
      Args: pchar;
    begin
      SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
      if SCManager = 0 then Exit;
      try
        Service := CreateService(SCManager, ServiceName, DisplayName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS or
    SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, pchar(FileName), nil, nil, nil, nil, nil);
        Args := nil;
        StartService(Service, 0, Args);
        CloseServiceHandle(Service);
      finally
        CloseServiceHandle(SCManager);
      end;
    end;
      

  6.   

    function PlainWinProc(hWnd:THandle; nMsg:UINT;
      wParam,lParam:Cardinal):Cardinal;export;stdcall;
    var
      Rect:TRect;
    begin
      result:=0;
      case nMsg of    wm_Create:
         begin
          CreateWindowEx(0,'Button','&HELLO',ws_Child or ws_Visible or
                            ws_Border or bs_PushButton,
                            0,0,80,30,hWnd,id_Button1,hInstance,nil);
          CreateWindowEx(0,'Button','&退出',ws_Child or ws_Visible or
                            ws_Border or bs_PushButton,
                            0,0,80,30,hWnd,id_Button2,hInstance,nil);
          CreateWindowEx(0,'Button','&安装服务',ws_Child or ws_Visible or
                            ws_Border or bs_PushButton,
                            0,0,80,30,hWnd,id_Button3,hInstance,nil);
          CreateWindowEx(0,'Button','&启动服务',ws_Child or ws_Visible or
                            ws_Border or bs_PushButton,
                            0,0,80,30,hWnd,id_Button4,hInstance,nil);
          CreateWindowEx(0,'Button','&停止服务',ws_Child or ws_Visible or
                           ws_Border or bs_PushButton,
                            0,0,80,30,hWnd,id_Button5,hInstance,nil);
          CreateWindowEx(0,'Button','&卸载服务',ws_Child or ws_Visible or
                            ws_Border or bs_PushButton,
                            0,0,80,30,hWnd,id_Button6,hInstance,nil);
         end;
        wm_Size:
         begin
          GetClientRect(hWnd,Rect);
          SetWindowPos(GetDlgItem(hWnd,id_Button1),0,Rect.Right div 2-215,
                       Rect.Bottom div 2-50,0,0,swp_NoZOrder or swp_NoSize);
          SetWindowPos(GetDlgItem(hWnd,id_Button2),0,Rect.Right div 2-65,
                     Rect.Bottom div 2-50,0,0,swp_NoZOrder or swp_NoSize);
          SetWindowPos(GetDlgItem(hWnd,id_Button3),0,Rect.Right div 2-300,
                     Rect.Bottom div 2-10,0,0,swp_NoZOrder or swp_NoSize);
          SetWindowPos(GetDlgItem(hWnd,id_Button4),0,Rect.Right div 2-200,
                     Rect.Bottom div 2-10,0,0,swp_NoZOrder or swp_NoSize);
          SetWindowPos(GetDlgItem(hWnd,id_Button5),0,Rect.Right div 2-100,
                     Rect.Bottom div 2-10,0,0,swp_NoZOrder or swp_NoSize);
          SetWindowPos(GetDlgItem(hWnd,id_Button6),0,Rect.Right div 2,
                     Rect.Bottom div 2-10,0,0,swp_NoZOrder or swp_NoSize);
         end;   wm_Command:               //按键触发
        case    LoWord(wParam) of
         id_Button1:
           begin
             if HiWord(wParam)=bn_Clicked then
              MessageBox(hWnd,'OK','Demo',MB_OK);
           end;
         id_Button2:
              begin
                if HiWord(wParam)=bn_Clicked then          end;
         id_Button3:            //安装
              begin
                if HiWord(wParam)=bn_Clicked then
                   InstallService(ServiceName, '1111', 'D:\Program Files\Tencent\QQ2009\Bin\QQ.exe');
              end;
         id_Button4:            //启动
              begin
                if HiWord(wParam)=bn_Clicked then
                     AControlService(ServiceName,7);
              end;
         id_Button5:            //停止
              begin
                if HiWord(wParam)=bn_Clicked then
                     AControlService(ServiceName,8);
              end;
         id_Button6:            //卸载
              begin
               if HiWord(wParam)=bn_Clicked then
                    AControlService(ServiceName,9);
              end;
         end;    wm_DropFiles:
          begin
            MessageBox(hWnd,'Drop File','Plain API',MB_OK);
            DragFinish(wParam);
          end;    wm_Destroy:
             PostQuitMessage(0);
        else
          result:=DefWindowProc(hWnd,nMsg,wParam,lParam);
      end;
    end;procedure WinMain;
    var
      hWnd,hWnd2:THandle;
      Msg:TMsg;
      Rect:TRect;
      WndClassEx:TWndClassEx;
      wParam:Cardinal;
    begin
      WndClassEx.cbSize:=SizeOf(TWndClassEx);
      WndClassEx.lpszClassName:='PlainWindow';
      WndClassEx.style:=CS_HREDRAW or CS_VREDRAW;
      WndClassEx.hInstance:=Hinstance;
      WndClassEx.lpfnWndProc:=@PlainWinProc;
      WndClassEx.cbClsExtra:=0;
      WndClassEx.cbWndExtra:=0;
      WndClassEx.hIcon:=LoadIcon(Hinstance,Pchar('MAINICON'));
      WndClassEx.hIconSm:=LoadIcon(Hinstance,Pchar('MAINICON'));
      WndClassEx.hCursor:=LoadCursor(0,idc_Arrow);
      WndClassEx.hbrBackground:=GetStockObject(black_Brush);
      WndClassEx.lpszMenuName:=nil;  if RegisterClassEx(WndClassEx)=0 then
      begin
        MessageBox(0,'Invaild Class registration','Plain API',MB_OK);
        exit;
      end
      else begin
        hWnd:=CreateWindowEx( WS_EX_ACCEPTFILES,
                             WndClassEx.lpszClassName,
                             'Demo',ws_OverlappedWindow,
                             cw_UseDefault,0,cw_UseDefault,0,0,0,
                             Hinstance,nil);
        if hWnd=0 then
          MessageBox(0,'Window not Created','Plain API',MB_OK)
        else begin
          ShowWindow(hwnd,SW_ShowNormal);
          while GetMessage(Msg,0,0,0) do
             begin
                TranslateMessage(Msg);
                DispatchMessage(Msg);
             end;
          end;
       end;
    end;begin
       WinMain;
    end.