delphi 如何把自身写入系统服务自启动?

delphi 如何把自身写入系统服务自启动?,第1张

要写注册表才能完成这个功能

先在uses 里面加入registry

procedure config(start:boolean //设置自动启动,start为true为允许自动启动,为false不自动启动

var

reg:Tregistry

begin

reg:=Tregistry.Create

reg.RootKey:=HKEY_LOCAL_MACHINE

if start=true then begin

if reg.OpenKey('\SOFTWARE\Microsoft\windows\CurrentVersion\Run',true) then

Reg.writeString('自动运行',Application.ExeName)

reg.CloseKey

end else begin

if reg.OpenKey('\SOFTWARE\Microsoft\windows\CurrentVersion\Run',true) then

Reg.DeleteValue('自动运行')

reg.CloseKey

end

end

Delphi服务程序注册与卸载

uses winsvc

function InstallService(ServiceName, DisplayName, FileName: string): boolean

var

SCManager,Service: THandle

Args: pchar

begin

Result := False

SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS)

if SCManager = 0 then Exit

try

Service := CreateService(SCManager, //句柄

PChar(ServiceName), //服务名称

PChar(DisplayName), //显示服务名

SERVICE_ALL_ACCESS, //服务访问类型

SERVICE_WIN32_OWN_PROCESS, //服务类型 or SERVICE_INTERACTIVE_PROCESS

SERVICE_AUTO_START, //自动启动服务

SERVICE_ERROR_IGNORE, //忽略错误

PChar(FileName), //启动的文件名

nil, //name of load ordering group (载入组名) 'LocalSystem'

nil, //标签标识符

nil, //相关性数组名

nil, //帐户(当前)

nil)//密码(当前)

Args := nil

StartService(Service, 0, Args)

CloseServiceHandle(Service)

finally

CloseServiceHandle(SCManager)

end

Result := True

end

procedure UninstallService(ServiceName: string)

var

SCManager,Service: THandle

ServiceStatus: SERVICE_STATUS

begin

SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS)

if SCManager = 0 then Exit

try

Service := OpenService(SCManager, PChar(ServiceName), SERVICE_ALL_ACCESS)

ControlService(Service, SERVICE_CONTROL_STOP, ServiceStatus)

DeleteService(Service)

CloseServiceHandle(Service)

finally

CloseServiceHandle(SCManager)

end

end

procedure ServiceCtrlHandler(Control: dword)stdcall

begin

case Control of

SERVICE_CONTROL_STOP:

begin

Stopped := True

Status.dwCurrentState := SERVICE_STOPPED

end

SERVICE_CONTROL_PAUSE:

begin

Paused := True

Status.dwcurrentstate := SERVICE_PAUSED

end

SERVICE_CONTROL_CONTINUE:

begin

Paused := False

Status.dwCurrentState := SERVICE_RUNNING

end

SERVICE_CONTROL_INTERROGATE:

SERVICE_CONTROL_SHUTDOWN: Stopped := True

end

SetServiceStatus(StatusHandle, Status)

end

系统服务都是运行后台的无窗口程序,如驱动等。系统服务装载的时候,Windows 界面接口、字体驱动还没有装载,所以你的程序不可能出现,因为你的程序有窗口(Tform)。等到进入Windows时,你的程序的生命期(加载字体)过程已经过去,所以你根本看不到什么。

注册表run里面的程序是Windows界面驱动装载以后运行的,(加入Windows有登录框,那么就是登录框以后)带窗口的程序放在这里就可以了。

服务和界面程序有相同之处,也有不同之处。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/11380905.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-15
下一篇 2023-05-15

发表评论

登录后才能评论

评论列表(0条)

保存