Windows NT、Windows 2000、Windows XP 都可以把程序做为服务启动。Delphi 也有向导直接帮助建立服务应用程序。当一个服务应用程序被建立后,就可以使用服务安装功能安装它。一个服务应用程序,必须完成 2 个关键的函数,即:StartServiceCtrlDispatcher 和 RegisterServiceCtrlHandler 后才能被系统做为服务启动。当使用 Delphi 向导建立服务应用程序时,这 2 个函数是被封装了的,不需要做其他的处理,但如果手工建立一个服务应用,就必须手工编写它。StartServiceCtrlDispatcher 函数的目的是告诉系统,这个服务应用的入口主函数。系统在启动服务时,就去执行这个函数指定的主入口函数,在主入口函数中,完成另一个函数的调用 RegisterServiceCtrlHandler ,这个函数是注册一个应用服务控制函数,以便系统可以控制这个服务应用。
安装一个服务应用是很简单的,代码如下: function InstallService:Boolean; var schSCManager,schService:THANDLE; strDir:array[0..1023]of char; lpszBinaryPathName:PChar; begin schSCManager:=OpenSCManager(nil,nil,SC_MANAGER_ALL_ACCESS); if schSCManager=0 then begin MessageBox(0,’联接服务控制管理器失败’,’Error’,MB_OK); Result:=false; exit; end; GetCurrentDirectory(1024,strDir); // 取到应用程序所在的目录 strlcat(strDir,’\ScvProject.exe’,1024); // 当前目录下的服务应用 lpszBinaryPathName:=strDir; schService:=CreateService( schSCManager, // 服务控制管理句柄 ’MyService’, // 服务名称 需要和 服务应用名 相同 ’My Service Display Name’, // 显示的服务名称 SERVICE_ALL_ACCESS, // 存取权利 SERVICE_WIN32_OWN_PROCESS, // 服务类型 SERVICE_DEMAND_START, // 启动类型 SERVICE_ERROR_NORMAL, // 错误控制类型 lpszBinaryPathName, // 服务程序 nil, // 组服务名称 nil, // 组标识 nil, // 依赖的服务 nil, // 启动服务帐号 nil); // 启动服务口令 if schService = 0 then begin MessageBox(0,’无法建立指定的服务对象’,’Error’,MB_OK); Result:=false; exit; end; CloseServiceHandle(schService); MessageBox(0,’已经成功地安装了服务对象’,’信息’,MB_OK); Result:=true; end;
删除一个服务的代码如下: function UnInstallService:Boolean; var schSCManager:THANDLE; hService:SC_HANDLE; begin schSCManager:=OpenSCManager(nil,nil,SC_MANAGER_ALL_ACCESS); if schSCManager=0 then begin MessageBox(0,’联接服务控制管理器失败’,’Error’,MB_OK); Result:=false; exit; end; hService:=OpenService(schSCManager,’MyService’,SERVICE_ALL_ACCESS); if hService=0 then begin MessageBox(0,’联接服务数据库失败’,’Error’,MB_OK); Result:=false; exit; end; if not DeleteService(hService) then begin MessageBox(0,’无法删除指定的服务对象’,’Error’,MB_OK); Result:=false; exit; end; if not CloseServiceHandle(hService) then begin MessageBox(0,’无法关闭服务控制器数据库’,’Error’,MB_OK); Result:=false; exit; end else begin MessageBox(0,’反安装服务成功’,’信息’,MB_OK); Result:=true; end; end; 注意使用这两个函数时,要 uses WinSvc 这个单元。 这两个函数中,其中: ’MyService’ 是用 Delphi 向导建立服务应用时在属性编辑器中的 ServiceStartName = ’MyService’ ; ’\ScvProject.exe’ 就是用 Delphi 向导建立的服务应用程序 ; ’My Service Display Name’ 将显示在系统服务列表中。 (出处:DelphiFans.com)
[1] [2] 下一页
|