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’ 将显示在系统服务列表中。 }