其他语言

位置:IT落伍者 >> 其他语言 >> 浏览文章

Delphi开发Windows服务程序


发布日期:2020年09月12日
 
Delphi开发Windows服务程序

开发步骤:

New>Other>Service Application

现在一个服务程序的框架已经搭起来了打开Service窗口有几个属性说明一下

AllowPause:是否允许暂停

AllowStop: 是否允许停止

Dependencies: 设置服务的依存关系服务的启动是否依赖于某个服务或者组

DisplayName: 在服务窗口显示的名称

Interactive: 设置为true时可以和Windows桌面进行交互如果我们想在服务里显示窗体的话此设置就要设置为true另外ServiceType必须为stWin

Password: 密码

StartType: 启动方式

如果我们想让服务与窗体交互步骤如下

在工程中新建一个窗体fmMain

然后在Service的OnStart中写代码

procedure TServiceServiceStart(Sender: TService; var Started: Boolean);

begin

Started := True;

SvcmgrApplicationCreateForm(TFmMain fmMain);

FmMainshow;

end;

OnStop的代码

procedure TServiceServiceStop(Sender: TService; var Stopped: Boolean);

begin

Stopped := True;

FmMainFree;

end;

这样在服务启动的时候就会显示出新建的那个窗体

编译完成后我们可以安装服务了安装方法为

在cmd窗口中执行 appname /install

如F:\Book\DService\Projectexe /install

这样服务就安装完成了

同样删除时也是在cmd窗口输入命令 appname /uninstall

如F:\Book\DService\Projectexe /uninstall

关于其他

关于服务程序的调试

如果我们开发的服务有多个窗体程序的调试无疑是个大问题

其实服务程序稍微一改就能改成一个标准的Win工程为了防止不停的变来变去我们可以加上一个编译条件通过编译条件来切换生成服务程序还是普通可执行程序假设编译条件为 NormalApp在以下几个地方需要加入编译条件

工程文件中单元的引用

{$IFDEF NormalApp}

Forms

{$ELSE}

SvcMgr

{$ENDIF}

工程初始化

{$IFDEF NormalApp}

ApplicationInitialize;

ApplicationCreateForm(TFmMain FmMain);

ApplicationRun;

{$ELSE}

if not ApplicationDelayInitialize or ApplicationInstalling then

ApplicationInitialize;

ApplicationCreateForm(TService Service);

ApplicationRun;

{$ENDIF}

这样我们就可以通过增加/删除NormalApp的编译条件来切换服务程序和普通窗口程序了

上一篇:Delphi7.0常用函数速查手册

下一篇:Delphi中两个BUG的分析与修复